Bla*_*ger 5 javascript angularjs angularjs-orderby
orderBy在这个问题中使用随机排序技术在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();
}
}
Run Code Online (Sandbox Code Playgroud)
但是在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"]]
Run Code Online (Sandbox Code Playgroud)
该文档orderBy没有使用函数表达式的示例,只有字符串表达式.有什么改变,或者这是一个错误?
我不确定以前的版本,但在当前版本中,在作用域上观看的任何表达式,例如传递给ng-repeat它的表达式,通常每个摘要至少评估两次.摘要周期仅在所有评估表达式的结果(在整个Angular应用程序的所有范围内)在两个连续评估之间相同时结束.
因为每次评价
<li ng-repeat="i in list | orderBy:random">{{i}}</li>
Run Code Online (Sandbox Code Playgroud)
导致对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()
});
});
Run Code Online (Sandbox Code Playgroud)
然后按以下方式使用该字段进行排序:
<li ng-repeat="i in rankedList | orderBy:'rank'">{{i.item}}</li>
Run Code Online (Sandbox Code Playgroud)
这可以在这个jsfiddle看到.
| 归档时间: |
|
| 查看次数: |
3641 次 |
| 最近记录: |