1

In my index.html page i have a navbar with two items and with angularjs i want set class "active" the selected item.

I have implemented the solution here:

StackOverflow solution

<div class="collapse navbar-collapse" ng-controller="HeaderController">
<ul class="nav navbar-nav">
    <li ng-class="{ active: isActive('/')}"><a href="/">Home</a></li>
    <li ng-class="{ active: isActive('/dogs')}"><a href="/dogs">Dogs</a></li>
    <li ng-class="{ active: isActive('/cats')}"><a href="/cats">Cats</a></li>
</ul>

function HeaderController($scope, $location) 
{ 
    $scope.isActive = function (viewLocation) { 
       return viewLocation === $location.path();
   };
}

and it works but the function isActive is called many and many times (here more than three) during the page rendering.

Why this behaviour?

Community
  • 1
  • 1
Tom
  • 4,007
  • 24
  • 69
  • 105
  • Are you sure you only have one use of the HeaderController? How many times is it being called? Is it only with the parameters you have listed above? Can you create an example snippet/fiddle/plnkr? – Brocco Nov 17 '14 at 20:01
  • 2
    This is because during digest loop `isActive` is going to be called at lease twice for every `li` to make sure that model is not changing anymore (stable). You have 3 li tags => isActive will be called at lease 6 times :) – dfsq Nov 17 '14 at 20:16
  • SO if i have 12 menu items the isActive is called 24 times? Where i can learn this behaviour on angularjs doc? – Tom Nov 17 '14 at 20:31
  • @Tom https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$digest – Vadim Nov 17 '14 at 21:06

0 Answers0