初始化变量一次以prevent" 10 $摘要()迭代达到"初始化、变量、摘要、迭代

2023-09-13 02:36:29 作者:那季花落丶乱了流年

我做了NG-重复了由控制器中声明的函数返回一个列表,我得到10 $摘要()迭代达到。中止!消息。

I'm doing a ng-repeat over a list returned by a function declared in the controller and I'm getting "10 $digest() iterations reached. Aborting!" message.

<div ng-repeat element in list()></div>

功能:

MyCtrl = ($scope)->
    ...
    $scope.list = ->
        list = {}
        for e in someArray
            ....    #adding stuff to list
        list
    ...

我发现这个问题是 $ scope.list()函数被调用好几次,每次调用函数的局部上榜时间变量被重新分配,这样的角度看到不同的对象,每次和ngRepeat元素重绘。我怎样才能避免这种情况?

I discovered the problem is the $scope.list() function is being called several times and each time the function is called the local list variable is re-assigned so angular sees a different object each time and the ngRepeat element is redrawn. How can I avoid this?

推荐答案

角前pressions评估每每$至少两次消化和$消化可以一次运行10次(当绑定需要刷新)。这意味着,前pressions将过度重新评估多次。这是棱角分明常见的陷阱之一。所以,你需要确保你不要在你的前pressions直接调用函数。相反,具备的功能执行一次,控制器里面,不是使用函数结果中的前pression:

Angular expressions are evaluated at least two times per each $digest and $digest can run 10 times at a time (when bindings need to be "refreshed"). This means that expressions will be re-evaluated many times over. This is one of the common pitfall with Angular. So you need to make sure you don't call functions directly in your expressions. Instead, have the function executed once, inside the controller, and than use the function result in the expression:

function MyCtrl($scope){

  function makeList(){
    var list = [];
    // do some logic to generate a list
    return list;
  };

  $scope.list = makeList();
}

<div ng-repeat="element in list"></div>

如果你的包含即可直接调用范围比方法,确保这些方法是幂等。

In case you have to call the scope methods directly than make sure the methods are idempotent.