我有一个显示navbar
的{{1}},当您点击它们时,country names
应显示出来。
map
目前<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>
是硬编码的。
array of countries
现在应该显示相应地图的 var app = angular.module('app',[]);
app.controller('appCtrl',function($scope){
// Countries
$scope.countries = [{
id: 1,
label: 'Italy',
coords: '41.29246,12.5736108'
}, {
id: 2,
label: 'Japan',
coords: '37.4900318,136.4664008'
}, {
id: 3,
label: 'USA',
coords: '37.6,-95.665'
}, {
id: 4,
label: 'India',
coords: '20.5937,78.9629'
}];
});
就像:
custom directive
并且
<div>
<country-tab-bar></country-tab-bar>
</div>
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){
}
}
}
});
As it is hard coded coordinates , it only shows one map of Italy. But I want to make it to show respective maps passing coordinates .
中的名称也应更改为反映当前国家/地区。
如何实现同样的目标?
请提供必要的解释。
答案 0 :(得分:0)
您可以达到以下所需
您需要先将国家/地区标签和国家/地区标记从html传递到指令。
<country-tab-bar coords="countryTab.coords" country="countryTab.label"></country-tab-bar>
接收指令范围内的值。
scope: {
coords: '=coords',
country: '=country',
}
链接部分中的使用这些范围成员并更新模板URL。将其附加到元素(这是应用指令的html标记)。最后编译它。
var app = angular.module('app',[]);
app.controller('appCtrl',function($scope){
// Countries
$scope.countries = [{
id: 1,
label: 'Italy',
coords: '41.29246,12.5736108'
}, {
id: 2,
label: 'Japan',
coords: '37.4900318,136.4664008'
}, {
id: 3,
label: 'USA',
coords: '37.6,-95.665'
}, {
id: 4,
label: 'India',
coords: '20.5937,78.9629'
}];
});
app.directive('countryTabBar', function($compile){
return {
restrict: ';E',
scope: {
coords: '=coords',
country: '=country',
},
link : function(scope,element){
var template = '<div ng-click="show()">'+scope.country+'</div><img ng-src="https://maps.googleapis.com/maps/api/staticmap?center='+scope.coords+'&zoom=4&size=800x200">';
element.append(template);
$compile(element.contents())(scope);
}
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app" ng-controller="appCtrl">
<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" style="cursor:pointer">
<country-tab-bar coords="countryTab.coords" country="countryTab.label"></country-tab-bar>
</li>
</ul>
</div>
</nav>
</body>
&#13;