Search code examples
javascriptangularjsduplicatesangularjs-ng-repeatng-class

angular: ng-class in ng-repeater , duplicate call


first of all sorry for my English. my problem is:

i've this simple code:

<li ng:repeat="item in menu.items" ng:class="getMenuItemClass(item)"> 
<a ng:href="#{{item.url}}">{{item.label}}</a>
</li>

and this my getMenuItemClass:

scope.getMenuItemClass = function(item) {
   console.log(item)
   var hashPath = $location.hashPath || '/';
   if (hashPath === item.url) {
      return 'selected';
   }
   return '';
};

this is the example ready, i don't know why, but in my real application it's triplicate! :0 can someone explain to me if i'm making a mistake?

http://jsfiddle.net/h7yKr/44/

I've update the jsfddle to the last version of angular, and now it's quadruplicate! watch it http://jsfiddle.net/h7yKr/46/

edit for clarication: the problem is that getMenuItemClass() is called a lot more times more then required, try to open the jsfiddle and open the browser console and watch the console.log!


Solution

  • Angular can evaluate an expression multiple times during a digest cycle and hence execution of function happens again and again.

    As explained in the documentation here

    Angular enters the $digest loop. The loop is made up of two smaller loops which process $evalAsync queue and the $watch list. The $digest loop keeps iterating until the model stabilizes, which means that the $evalAsync queue is empty and the $watch list does not detect any changes.

    Since you $watch expression is a function it can get called multiple time.

    Alternatively look at $routeChangeStart event in $route service. You can subscribe to this event. Create a variable on your scope and do the ng-class binding to that variable