random orderBy in AngularJS 1.2 returns 'infdig' errors

后端 未结 2 474
别那么骄傲
别那么骄傲 2020-11-29 13:45

Using the random orderBy sort technique in this question works fine in AngularJS 1.1.

var myApp = angular.module(\'myApp\',[]);

function MyCtr         


        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-29 14:17

    I'm not sure about previous versions, but in the current version, any expression watched on a scope, such as that passed to ng-repeat is usually evaluated at least twice per digest. The digest cycle only finishes when the results of all evaluated expressions, across all scopes of the entire Angular app, are identical between two successive evaluations.

    Because each evaluation of

  • {{i}}
  • results in calls to random(), and so a different order, then Angular will keep on evaluating the expressions, until it hits its limit of 10 digest iterations, and throws an error.

    The solution to this is to set the order outside of the template, in the controller:

    $scope.list = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
    $scope.rankedList = [];
    angular.forEach($scope.list, function(item) {
        $scope.rankedList.push({
            item: item,
            rank: 0.5 - $window.Math.random()
        });
    });
    

    And then order using the field by something like:

  • {{i.item}}
  • This can be seen at this jsfiddle .

提交回复
热议问题