ng-repeat runs twice (Angular) [duplicate]

笑着哭i 提交于 2019-12-20 06:31:11

问题


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>


来源:https://stackoverflow.com/questions/27178164/ng-repeat-runs-twice-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!