AngularJS中的自定义指令 [英] Custom Directives in AngularJS
问题描述
在导航栏中,只要我们单击国家/地区名称,相应的地图就会出现在屏幕上.
In a navbar whenever we click on a country name the respective map should appear on the screen .
到目前为止,国家/地区坐标已硬编码到我建立的指令中.但是我无法使指令显示在屏幕上.
As of now , the country coordinates are hard coded into the directive I built. But I am not able to make directive displayed on the screen.
我知道,我缺少一些非常基本的东西,但直到现在我还是无法弄清楚.
I know , I am missing something very basic but I could not figure it out till now.
<body>
<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-click="itemClicked(countryTab.label)" style="cursor:pointer">
<a>{{countryTab.label}}</a>
<country-tab-bar country="selectedCountry"></country-tab-bar>
</li>
</ul>
</div>
</nav>
<script>
var app = angular.module('app',[]);
app.controller('appCtrl',function($scope){
$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(){
return {
restrict: 'E',
scope:{
country: '='
},
template: '<div>'+
' <div>Italy</div>'+
' <br/>'+
' <img ng-src="https://maps.googleapis.com/maps/api/staticmap?center={{country.coords}}&zoom=4&size=800x200"> '+
'</div>',
link : function(scope,elem,attrs){
scope.itemClicked = function(value){
scope.selectedCountry = value;
}
}
}
});
</script>
</body>
当我点击国家名称时,什么也没有发生.用户界面也搞砸了.
Nothing happens when I click on the country names . Also the UI is screwed up.
我想念的最基本的东西是什么?
What is the basic thing that I am missing ?
请给出相同的解释.我对Angular非常陌生.
Please give an explanation for the same. I am pretty much new to Angular.
推荐答案
您的指令标记如下所示,该标记应包含所选国家/地区.
You directive tag will look something like below, which expect selected country.
<div ng-if="selectedCountry">
<country-tab-bar country="selectedCountry"></country-tab-bar>
<div>
然后在控制器内具有 itemClicked
,该控制器将具有 selectedCountry
then have itemClicked
inside a controller which will have selectedCountry
scope.itemClicked = function(value){
$scope.selectedCountry = value;
}
指令
app.directive('countryTabBar',function(){
return {
restrict: ';E',
templateUrl: 'countryDirective.tpl.html',
scope : {
country: '='
}
}
});
countryDirective.tpl.html
<div>
<div>{{country.label}}</div>
<img ng-src="https://maps.googleapis.com/maps/api/staticmap?center={{country.coords}}&zoom=4&size=800x200">
</div>
这篇关于AngularJS中的自定义指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!