ng-repeat 运行两次(Angular) [英] ng-repeat runs twice (Angular)

查看:31
本文介绍了ng-repeat 运行两次(Angular)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下 ng-repeat:

Consider the following ng-repeat:

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

现在奇怪的是,如果我有一个包含 10 个项目的数组,getName 会被调用 20 次

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

检查这个jsfiddle

有人可以解释为什么会发生这种情况.性能明智,这可能是一种杀戮(我可以想象)

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

推荐答案

这是 angular 的标准行为.Angular 会对值进行脏检查,并且至少会运行两次以确保值没有改变.

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.

为了避免这种行为,我建议在控制器中映射这个名称,这只会为每个项目评估一次:

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>

这篇关于ng-repeat 运行两次(Angular)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆