我设法创建了一个小例子,它可以直接使用并可以重现问题。它是一个滤波器,可以消除一个数组随机2元素:
<!DOCTYPE html>
<html ng-app='myApp'>
<head>
<meta charset="utf-8" />
<script src="https://code.angularjs.org/1.6.5/angular.js"></script>
<script>
angular.module('myApp', [])
.filter('random', function() {
return function(input) {
var a = Math.floor(Math.random()*input.length);
var b = Math.floor(Math.random()*input.length);
return input.filter(function(element, i){
if (i !== a && i !== b){
return element;
}
});
};
})
.controller('Controlleur', function($scope) {
$scope.contacts = [
{"name": "donatello", "tel": 12456},
{"name": "michaelangelo", "tel": 12456},
{"name": "leonardo", "tel": 12456},
{"name": "raphael", "tel": 12456},
{"name": "robert", "tel": 12456},
]
});
</script>
</head>
<body ng-controller="Controlleur">
<ul>
<li ng-repeat="contact in contacts|random track by contact.name ">
<strong>{{contact.name}}</strong>: {{contact.tel}}
</li>
</ul>
</body>
</html>
复制/粘贴,在一个文件中,加载在浏览器中的文件,并打开控制台。如果按F5键的时候了几个号码,你会看到的筛选器的工作,但你会随机得到:
Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: [[{"msg":"fn: regularInterceptedExpression","newVal":21,"oldVal":18},{"msg":"fn: regularInterceptedExpression","newVal":"raphael"},{"msg":"fn: regularInterceptedExpression","newVal":"12456"},{"msg":"fn: regularInterceptedExpression","newVal":"robert"},{"msg":"fn: regularInterceptedExpression","newVal":"12456"}],
...
的问题是,它通常意味着$消化的连续触发次数太多。但是,我不会在任何地方明确更新范围。我只是在一个过滤器中创建一个新的数组,具有如此明显的副作用。
您正在遍历联系人并同时对其进行筛选。这意味着你正在改变你正在迭代的数组。如果角度循环通过这个数组,并且它正在变化,那么也许你遇到了麻烦。我不会在这个地方使用过滤器。 –
我不更改数组。 array.filter()生成一个新的数组。第一个没有修改。 –