Javascript 在AngularJS中将参数传递给自定义指令
我有一个Javascript 在AngularJS中将参数传递给自定义指令,javascript,angularjs,Javascript,Angularjs,我有一个导航栏,显示了几个国家的名称,当你点击它们时,相应的地图就会显示出来 <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="#">Welcome to the world of directives!&
导航栏
,显示了几个国家的名称
,当你点击它们时,相应的地图
就会显示出来
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">Welcome to the world of directives!</a>
</div>
<ul class="nav navbar-nav">
<li ng-repeat="countryTab in countries" ng-clicked="itemClicked(countryTab)" style="cursor:pointer">
<a>{{countryTab.label}}</a></li>
</ul>
</div>
</nav>
现在应该显示相应映射的自定义指令
,如下所示:
<div>
<country-tab-bar></country-tab-bar>
</div>
及
app.directive('countryTabBar',function(){
返回{
限制:';E',
模板:“”+
“意大利”+
“
”+
' '+
'',
链接:功能(范围){
scope.itemClicked=函数(值){
}
}
}
});
因为它是硬编码坐标,所以它只显示了一张意大利地图。但我想让它显示通过坐标的各个地图。
div
中的名称也应更改以反映当前国家/地区
如何实现同样的目标
请提供必要的解释。您可以实现如下所示的目标 首先需要将国家标签和国家坐标从html传递到指令
<country-tab-bar coords="countryTab.coords" country="countryTab.label"></country-tab-bar>
在链接部分中,使用这些作用域成员并更新模板URL。将其附加到元素(这是应用该指令的html标记)。并最终编译它
var-app=angular.module('app',[]);
app.controller('appCtrl',函数($scope){
//国家
$scope.countries=[{
id:1,
标签:“意大利”,
坐标:“41.29246,12.5736108”
}, {
id:2,
标签:"日本",,
坐标:“37.4900318136.4664008”
}, {
id:3,
标签:“美国”,
坐标:'37.6,-95.665'
}, {
id:4,
标签:“印度”,
坐标:“20.5937,78.9629”
}];
});
app.directive('countryTabBar',函数($compile){
返回{
限制:';E',
范围:{
coords:'=coords',
国家:'=国家',
},
链接:功能(范围、元素){
变量模板=''+范围.国家+'';
元素。追加(模板);
$compile(element.contents())(范围);
}
}
});代码>
-
这与您的上一个问题类似,您是否看过我提供的答案(我想这可能会解决您的问题)。。你不应该无缘无故地多次问同一个问题。@PankajParkar非常感谢。请您解释一下范围
对象中的城市
是什么,以及您在链接函数中到底想做什么?
app.directive('countryTabBar',function(){
return {
restrict: ';E',
template: '<div>'+
' <div>Italy</div>'+
' <br/>'+
' <img ng-src="https://maps.googleapis.com/maps/api/staticmap?center=41.29246,12.5736108&zoom=4&size=800x200"> '+
'</div>',
link : function(scope){
scope.itemClicked = function(value){
}
}
}
});
<country-tab-bar coords="countryTab.coords" country="countryTab.label"></country-tab-bar>
scope: {
coords: '=coords',
country: '=country',
}