Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

angularjs - angular Infinite $digest Loop in ng-repeat

I want to call function in ng-repeat attribute, here is my code

example plnkr

html

<body ng-controller="mainCtrl">
  <div ng-repeat='item in getGroupedRange() track by item.id'>
    <span>{{item.val}}</span>
    <span>{{item.abs}}</span>
    <span>{{item.rel}}</span>
    <span>{{item.cum}}</span>
  </div>
</body>

js

$scope.getGroupedRange = function() {
    return [
      {
        val: 1,
        abs: 1,
        rel: 1,
        cum: 1,
        id: 123456
      }
    ];
  };

When I opened console I noticed the error

10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: [[{"msg":"fn: function (c,d,e,f){e=a(c,d,e,f);return b(e,c,d)}","newVal":9,"oldVal":8}],[{"msg":"fn: function (c,d,e,f){e=a(c,d,e,f);return b(e,c,d)}","newVal":10,"oldVal":9}],[{"msg":"fn: function (c,d,e,f){e=a(c,d,e,f);return b(e,c,d)}","newVal":11,"oldVal":10}],[{"msg":"fn: function (c,d,e,f){e=a(c,d,e,f);return b(e,c,d)}","newVal":12,"oldVal":11}],[{"msg":"fn: function (c,d,e,f){e=a(c,d,e,f);return b(e,c,d)}","newVal":13,"oldVal":12}]]

The main goal of my code is using function in ng-repeat for calculating data in each event loop

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No, you can't use function in ngRepeat like this. The problem is that Angular uses strict comparison of objects in digest loop to determine if the value of the property changed since the last check. So what happens is that getGroupedRange returns new value (new array) each time it's called. Angular has no idea and considers this value as unstable and thus continues checking. But it aborts after 10 checks.

You need to construct necessary array and assign it to scope property, so it will not change during digest loop:

$scope.groupedRange = $scope.getGroupedRange();

then use it like in ngRepeat

  <div ng-repeat='item in groupedRange track by item.id'>
    <span>{{item.val}}</span>
    <span>{{item.abs}}</span>
    <span>{{item.rel}}</span>
    <span>{{item.cum}}</span>
  </div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...