-->

ng-repeat runs twice (Angular) [duplicate]

2019-03-04 16:08发布

问题:

This question already has an answer here:

  • Why is ng-style function applied twice? 2 answers

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)

回答1:

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>