http://plnkr.co/edit/dBe36L6vwOZOykujFRfg
在 Plunker 中,我遇到了以下 AngularJS 错误: "10 $digest() iterations reached. Aborting!"
当在 index.html 中使用时,该逻辑是可行的:
<h1>(working) Fruit from main document: {{vm.randomFruit().name}}</h1>
但是,当我尝试在指令中调用传入对象的类似代码时,会抛出错误:
<h1>(causing error) Fruit from directive template: {{fruit.name}}</h1>
在作用域函数中这样做,似乎不会导致指令抛出错误:
//this works for both instances
return vm.fruits[0];
然而,当我以任何方式触碰$scope.fruits时,即使只是复制它,它也会在指令版本上引发错误。
//something about touching the array here exposes the error, even though it still works
var x = [];
angular.copy(vm.fruits, x);
return x[0];
为什么会在这里抛出错误?似乎是某种循环依赖,但为什么只在指令版本上出现?
有没有更好的方法来使用指令、模板和传入的参数对象,使其更加标准化?
错误:已达到10次$digest()迭代。中止!最近5次迭代中触发了观察程序: [["fn: parentValueWatch; newVal:{\"name\":\"apple\"}; oldVal:{\"name\":\"apple\"}"], ["fn: parentValueWatch; newVal:{\"name\":\"apple\"}; oldVal:{\"name\":\"apple\"}"], ["fn: parentValueWatch; newVal:{\"name\":\"apple\"}; oldVal:{\"name\":\"apple\"}"], ["fn: parentValueWatch; newVal:{\"name\":\"apple\"}; oldVal:{\"name\":\"apple\"}"], ["fn: parentValueWatch; newVal:{\"name\":\"apple\"}; oldVal:{\"name\":\"apple\"}"]] at 错误(native) at Object.$digest (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.js:7925:19) at Object.$apply (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.js:8097:24) at done (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.js:9111:20) at completeRequest(https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.js:9274:7) at XMLHttpRequest.xhr.onreadystatechange (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.js:9244:11)
更新1
将aFruit()更新为randomFruit()以更好地演示我的问题:
$scope.randomFruit = function() {
//something about touching the array here exposes the error, even though it still works
var x = [];
angular.copy($scope.fruits, x);
//do some custom stuff here, sorting, etc. <whatever>
var randomIndex = Math.floor((Math.random() * x.length));
return x[randomIndex];
};
更新2
被告知不要使用$scope,因此已从控制器中完全删除它。仍然看到相同的错误。
myApp.controller('FruitCtrl', function() {
var vm = this;
vm.fruits = fruits;
vm.randomFruit = function() {
//something about touching the array here exposes the error, even though it still works
var x = [];
angular.copy(vm.fruits, x);
//do some custom stuff here, sorting, etc. <whatever>
var randomIndex = Math.floor((Math.random() * x.length));
return x[randomIndex];
};
});