AngularJS InfDig错误(无限循环),带有返回对象数组的ng重复函数



这是我的代码:

<h1 ng-repeat="item in func()">something</h1>
$scope.func = function(){
return [{"property" : "value1"},{"property": "value2"}];
}

在Angular.js诉1.1.1一案中,没有任何错误。在Angular.JS第1.2.1版中,我犯了一个infDig错误。

1.1.1版

1.2.1版的Fiddle

你能解释一下这种情况吗?非常感谢。

自AngularJS 1.2起:将"track-by"表达式添加到ng repeat中,更恰当地解决了这个问题,如图所示在以下代码中。

<h1 ng-repeat="item in func() track by $index">something</h1>
$scope.func = function(){
return [{"property" : "value1"},{"property": "value2"}];
}

下面的文章有助于更详细地理解这个表达式,以及为什么它如此有用,特别是在处理Ben Nadal的$$haskey Using Track By with ngRepeat in AngularJS 1.2时。

问题是每次都要创建一个新的数组,所以angular需要跟踪它。据我所知,ng-repeat运行,然后立即再次检查其集合,看看在该周期中是否有任何变化。因为函数返回了一个新数组,所以这被认为是一个更改。

看看这个:http://jsfiddle.net/kL5YZ/.如果查看console.log并单击按钮,您将看到每次重复运行时对象的$$hashKey属性都会发生更改。

更改从1.1.4版本开始,但更改日志没有提供任何线索来说明行为不同的原因。新的行为对我来说更有意义。

下面是我发现的一篇很好的文章,它深入解释了当前的行为:如何循环使用ng repeat函数返回的项?

如果确保每次都返回相同的对象/数组,则不会出现错误。您可以让函数缓存它基于参数创建的任何东西,并在传入这些参数时始终返回相同的数组/对象。因此,myFunc('fo')将始终返回相同数组,而不是看起来相同的新数组。请参阅下面代码中的注释实时演示(单击)

<div ng-repeat="foo in foos">
<div ng-repeat="bar in barFunc(foo)">{{bar.text}}</div>
<div ng-repeat="bar in barFunc('test')">{{bar.text}}</div>
</div>

JavaScript:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, myService) {
$scope.foos = [
'a','b','c'
];
//I put this into a service to avoid cluttering the controller
$scope.barFunc = myService.getObj;
});
app.factory('myService', function() {
/*
* anything created will be stored in this cache object,
* based on the arguments passed to `getObj`.
* If you need multiple arguments, you could form them into a string,
* and use that as the cache key
* since there's only one argument here, I'll just use that
*/
var cache = {};
var myService = {
getObj : function(val) {
//if we haven't created an array with this argument before
if (!cache[val]) {
//create one and store it in the cache with that argument as the key
cache[val] = [
{text:val}
];
}
//return the cached array
return cache[val];
}
};
return myService;
});

最新更新