小编典典

AngularJS 1.2中的random orderBy返回'infdig'错误

angularjs

orderBy在这个问题中使用随机排序技术在AngularJS1.1中工作正常。

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

function MyCtrl($scope) {
    $scope.list = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
    $scope.random = function() {
        return 0.5 - Math.random();
    }
}
不过,在1.2版中,它将infdig错误放入控制台,并需要更长的时间返回排序后的结果:http
//jsfiddle.net/mblase75/jVs27/

控制台中的错误如下所示:

Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: [["fn: $watchCollectionWatch; newVal: 42; oldVal: 36"],["fn: $watchCollectionWatch; newVal: 47; oldVal: 42"],["fn: $watchCollectionWatch; newVal: 54; oldVal: 47"],["fn: $watchCollectionWatch; newVal: 61; oldVal: 54"],["fn: $watchCollectionWatch; newVal: 68; oldVal: 61"]]

文档orderBy没有使用函数表达式的示例,仅使用字符串表达式。有什么变化,还是这是一个错误?


阅读 253

收藏
2020-07-04

共1个答案

小编典典

我不确定以前的版本,但是在当前版本中,在作用域上监视的任何表达式(例如传递给的表达式ng-repeat)通常每个摘要至少评估两次。仅当两次连续求值之间在整个Angular应用程序的所有范围内所有求值表达式的结果相同时,摘要循环才结束。

因为每次评价

<li ng-repeat="i in list | orderBy:random">{{i}}</li>

导致对random()的调用,并且顺序不同,然后Angular将继续评估表达式,直到达到10次摘要迭代的极限并引发错误。

解决方案是在控制器中的模板外部设置顺序:

$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()
    });
});

然后通过类似以下命令使用该字段:

<li ng-repeat="i in rankedList | orderBy:'rank'">{{i.item}}</li>

这可以在jsfiddle中看到。

2020-07-04