angular Infinite $digest Loop in ng-repeat

前端 未结 3 568
傲寒
傲寒 2020-12-19 07:53

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

example plnkr

html


  
相关标签:
3条回答
  • 2020-12-19 08:20

    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>
    
    0 讨论(0)
  • 2020-12-19 08:22

    Found the solution:

      $scope.prev = null;
      $scope.getGroupedRange = function() {
        var data = [{
          val: 1,
          abs: 1,
          rel: 1,
          cum: 1,
          id: 123456
        }];
        if (angular.equals($scope.prev, data)) {
          return $scope.prev;
        }
        $scope.prev = data;
        return data;
      };
    
    0 讨论(0)
  • 2020-12-19 08:23

    Angular will do calculation and automatic showing in template on data change for you. But by putting ng-repeat='item in getGroupedRange() you put this into endles cycle recalculation.

    Try to avoid this by assigning the value of the items (that may be changed by $scope.getGroupedRange function in any way) in the list to some scope variable, say $scope.range, that will be iterated in ng-repeat.

    in controller

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

    in template

     <div ng-repeat='item in range track by item.id'>
        <span>{{item.val}}</span>
        <span>{{item.abs}}</span>
        <span>{{item.rel}}</span>
        <span>{{item.cum}}</span>
      </div>
    
    0 讨论(0)
提交回复
热议问题