Angular新手。尝试创建可重用的指令,以便我可以跨页面共享导航标题栏。每个单独的html页面应该能够指定当前页面或活动页面的内容,因此应用css属性来区分该页面。
所有逻辑都应该包含在指令中,以便每个使用此导航栏的html页面只需要设置ActivePage的“属性”。
但是,我似乎无法在我的模板中获取条件ng-class来应用CSS类。有人能帮助我发现我的问题吗?
关于Plunker的示例:http://plnkr.co/edit/JTI8wLOhN5xWeDdD9i2l
使用中:
<section ng-app="NavBarApp" ng-controller="NavBarCtrl">
<nav-Bar ActivePage="{{Pages.Navigation.Page2}}"></nav-Bar>
</section>
使用Javascript:
var Pages = {};
Pages.Navigation = {};
Pages.Navigation.Page1 = {
Name: "Page 1",
BaseLink: "Page1.html"
};
Pages.Navigation.Page2 = {
Name: "Page 2",
BaseLink: "Page2.html"
};
Pages.Navigation.Page3 = {
Name: "Page 3",
BaseLink: "Page3.html"
};
var NavBarApp = angular.module('NavBarApp', []);
NavBarApp.controller('NavBarCtrl', function NavBarCtrl($scope){
$scope.Pages = {};
$scope.Pages.Navigation = Pages.Navigation;
});
NavBarApp.directive('navBar', function(){
return {
restrict: 'E',
replace: true,
scope: {
strActivePage: "@ActivePage"
},
controller: function($scope){
$scope.aryPagesList = [];
for(var strProp in Pages.Navigation){
$scope.aryPagesList.push(Pages.Navigation[strProp]);
}
},
templateUrl: 'NavBarTemplate.html'
};
});
模板:
<div id="NavBar" class="navigation">
<ul>
<li ng-repeat="oCurPage in aryPagesList">
<a id="{{oCurPage.Name}}" ng-class="{active: oCurPage.Name==strActivePage}" href="{{oCurPage.BaseLink}}">{{oCurPage.Name}}</a>
</li>
</ul>
</div>
提前致谢!
答案 0 :(得分:4)
Html / Angularjs不允许在属性名称中使用大写字符,因此将导航栏html更改为:
<nav-bar active-page="{{Pages.Navigation.Page2.Name}}"></nav-bar>
然后在您的指令范围内,您必须将@ActivePage更改为@activePage
NavBarApp.directive('navBar', function(){
return {
restrict: 'E',
replace: true,
scope: {
strActivePage: "@activePage"
},
controller: function($scope){
$scope.aryPagesList = [];
for(var strProp in Pages.Navigation){
$scope.aryPagesList.push(Pages.Navigation[strProp]);
}
},
templateUrl: 'NavBarTemplate.html'
};
});
您的plunkr已修改:http://plnkr.co/edit/6fMkmfxBd2I8nlfG8eLH