I was attempting to get AngularJs to apply an active class on a nav section depending upon the active route. My solution works fine but I noticed a curious behaviour -- more on that below. For now, here's how the active class is set in the HTML:
<ul class="menu" ng-controller="ControllerHeader">
<li><a ng-class="{ active: isActive('/foo') }" href="#/foo">foo</a></li>
<li><a ng-class="{ active: isActive('/bar') }" href="#/bar">bar</a></li>
<li><a ng-class="{ active: isActive('/baz') }" href="#/baz">baz</a></li>
</ul>
ControllerHeader and isActive are defined as given:
var app = angular.module('app', [ ]);
app.controller( 'ControllerHeader', ['$scope', '$location',
function ($scope, $location) {
$scope.isActive = function (location) {
// multiple logging occurs: exactly 3*3 times
console.log(location, $location.path());
return location === $location.path();
};
}
] );
The issue I've noticed is that isActive above is called 3 * 3 times! Could someone please explain why? How can I fix it that such that it is called once per item only?
$digestcycle is triggered, which is a lot. Unless it's causing performance issues, don't worry about it.