AngularJS 1.2 中的 random orderBy 返回“infdig"错误 [英] random orderBy in AngularJS 1.2 returns 'infdig' errors

查看:24
本文介绍了AngularJS 1.2 中的 random orderBy 返回“infdig"错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using the random orderBy sort technique in this question works fine in AngularJS 1.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/

In 1.2, though, it puts infdig errors into the console and takes a much longer time to return the sorted results: http://jsfiddle.net/mblase75/jVs27/

控制台中的错误看起来像:

The error in the console looks like:

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 的文档 没有使用函数表达式的例子,只有字符串表达式.有什么变化,还是这是一个错误?

The documentation for orderBy doesn't have an example of using function expressions, only string expressions. Did something change, or is this a bug?

推荐答案

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

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.

因为每次评价

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

导致对 random() 的调用,因此顺序不同,然后 Angular 将继续评估表达式,直到达到 10 次摘要迭代的限制,并抛出错误.

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:

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

这可以在这个 jsfiddle 看到.

This can be seen at this jsfiddle .

这篇关于AngularJS 1.2 中的 random orderBy 返回“infdig"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆