Angularjs: why is ng-repeat doing too much work?

Viewed 754

I don't understand why ng-repeat seems to be doing unnecessary work.

I have implemented a small navigation menu example to show what I mean. I have created an Angular module that contains a controller (NavCtrl), in which I:

  1. populate nav menu data in $scope, and
  2. create a function that returns a class based on whether or not the specified menu item is selected. Note: this is very much like the code from this Stackoverflow question, which looked like a great way to implement a general hash-based nav menu concept (please point me to a better concept if you know of one!).

I have created a JSFiddle of my example.

My question is this: why does the ng-repeat loop get executed three times? Notice the console-logging line in my Javascript method navClass. When I run it in Chrome and simply load the HTML, I get the following output:

evaluating route: home, against page: home testmod.js:29
evaluating route: home, against page: teams testmod.js:29
evaluating route: home, against page: events testmod.js:29
evaluating route: home, against page: venues testmod.js:29
evaluating route: home, against page: settings testmod.js:29
evaluating route: home, against page: home testmod.js:29
evaluating route: home, against page: teams testmod.js:29
evaluating route: home, against page: events testmod.js:29
evaluating route: home, against page: venues testmod.js:29
evaluating route: home, against page: settings testmod.js:29
evaluating route: home, against page: home testmod.js:29
evaluating route: home, against page: teams testmod.js:29
evaluating route: home, against page: events testmod.js:29
evaluating route: home, against page: venues testmod.js:29
evaluating route: home, against page: settings testmod.js:29

Looks to me like the ng-repeat loop is running three times, resulting in 15 lines of output against my 5-item example menu list, even though my markup looks like it should only iterate over the items once:

     <div>
        <ul ng-controller="navCtrl">
           <li ng-repeat="navLink in navLinks"> <a href='#/{{navLink.Title}}' ng-class="navClass('{{navLink.Title}}')">{{navLink.LinkText}}</a> </li>
        </ul>
     </div>

Explanation or constructive criticism highly appreciated!

1 Answers
Related