0

Consider the following ng-repeat:

<p ng-repeat="item in items">
    <span ng-bind="getName(item)"></span>
</p>

Now the weird thing is that if I have an array with 10 items, the getName is called 20 times

Checkout this jsfiddle

Can someone explain why this is happening. Performance wise this might be a killing (I can imagine)

Jeanluca Scaljeri
  • 26,343
  • 56
  • 205
  • 333

1 Answers1

3

This is standard behavior for angular. Angular runs dirty checking on values and will run at least twice to ensure that the value hasn't changed.

EDIT:

In order to avoid this kind of behavior I would suggest mapping this name in the controller, this will only be evaluated once for each item:

function MyCtrl($scope) {
    ...
    $scope.items.forEach(function(item) {
        item.name = getName(item);
    });
    ...
});


<p ng-repeat="item in items">
     <span>{{item.name}}</span>
</p>
Vadim
  • 17,897
  • 4
  • 38
  • 62