Reputation: 519
New to Angular. Trying to create a reusable directive so that I can share a navigation header bar across pages. Each separate html page should be able to specify what the current or active page is, thus a css property is applied distinguishing that page.
All the logic should be wrapped up in the directive so that each html page using this navigation bar should only have to set the 'property' of ActivePage.
However, I cannot seem to get the conditional ng-class in my template to apply the CSS class. Can someone help me spot my problem?
Example on Plunker: http://plnkr.co/edit/JTI8wLOhN5xWeDdD9i2l
In Use:
<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'
};
});
Template:
<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>
Thanks in advance!
Upvotes: 2
Views: 1640
Reputation: 28750
Html/Angularjs doesn't allow for capital characters in attribute names so change your nav-bar html to this:
<nav-bar active-page="{{Pages.Navigation.Page2.Name}}"></nav-bar>
And then in your scope for your directive, you have to change the @ActivePage to @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'
};
});
Your plunkr modified: http://plnkr.co/edit/6fMkmfxBd2I8nlfG8eLH
Upvotes: 4