I want to use the abilitie of ui-router to test the active state in a ng-class
If I try this it does not work :
navTest.$inject = ["$compile", "$navbar", "$state"];
function navTest($compile, $navbar, $state) {
var defaults = $navbar.defaults;
var navTest = {
restrict: 'E',
template: '<nav class="navbar navbar-default" role="navigation">' +
'<div class="container-fluid">' +
'<div class="navbar-header">' +
'<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">' +
'<span class="sr-only">Toggle navigation</span>' +
'<span class="icon-bar"></span>' +
'<span class="icon-bar"></span>' +
'<span class="icon-bar"></span>' +
'</button>' +
'<a class="navbar-brand" href="#">Brand</a>' +
'</div>' +
'<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">' +
'<ul class="nav navbar-nav">' +
'<li data-ng-class="{active: $state.includes(\'user\')}"><a data-ui-sref="user.List">Link 1</a></li>' +
'<li data-ng-class="{active: $state.includes(\'technology\')}"><a data-ui-sref="technology.List">Link 2</a></li>' +
'</ul>' +
'</div>' +
'</div>' +
'</nav>',
replace: true
};
return navTest;
}
Now if I add a function to test the active state in the "link" function (of the directive) and I replace : data-ng-class="{active: $state.includes(\'technology\')}" by data-ng-class="{active: isActiveState(\'technology\')}"
link : function (scope, elem, attrs) {
scope.isActiveState = function (name) {
return $state.includes(name);
};
}
Everything works fine but I don't understand why because the function does exactly the same thing ?
It's a scope thing but you don't want to use $rootScope
; putting the following in your link
function should be enough:
scope.$state = $state;