http://plnkr.co/edit/dBe36L6vwOZOykujFRfg
在插件中,我遇到以下角度错误:“已达到10个$ digest()迭代。正在中止!”
该逻辑在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:
{\“名称\”:\“苹果\”}; oldVal:{\“名称\”:\“苹果\”}“],[” fn:
parentValueWatch; newVal:{\“名称\”:\“苹果\”}; oldVal:
{\“名称\”:\“苹果\”}“],[” fn:parentValueWatch; newVal:
{\“名称\”:\“苹果\”}; oldVal:{\“名称\”:\“苹果\”}“],[” fn:
parentValueWatch; newVal:{\“名称\”:\“苹果\”}; oldVal:
{\“名称\”:\“苹果\”}“],[” fn:parentValueWatch; newVal:
{\“名称\”:\“苹果\”}; oldVal:{\“名称\”:\“苹果\”}“]]
错误(本机)
在Object。$ digest(https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.js:7925:19)
在Object。$ apply(https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.js:8097:24)
完成时(https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.js:9111:20)
在completeRequest(https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.js:9274:7)
在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];
};
});
最佳答案
问题在于方法,即如何将数据传递到Angular。 Angular具有很棒的数据绑定,它检查模型是否已更改并更新UI。 UI更新后,它将再次检查下一轮更改。如果数据始终更改,则可能会陷入循环。
在这种特殊情况下,Angular无法理解数据是相同的。它在每个摘要循环上接收新的数组,并假定数据已更改,更新UI并再次开始检查。
确保您没有在每个$ digest循环中从UI更新数组,也不在每个$ digest循环中返回新数组。
例如
这将调用无限循环:
$scope.aFruit= function() {
return [
{"name":"apple"},
{"name":"orange"},
{"name":"banana"},
];
};
这将正常工作,因为对数组的引用保持不变
var myFruits = return [
{"name":"apple"},
{"name":"orange"},
{"name":"banana"},
]
$scope.aFruit= function() {
myFruits;
};