作为AngularJS 1.2:加入的“轨道”表达到NG-重复和更适当地解决所证明在下面的代码 这个问题。
<h1 ng-repeat="item in func() track by $index">something</h1>
$scope.func = function(){
return [{"property" : "value1"},{"property": "value2"}];
}
下面的文章有助于了解更详细的表达,为什么它是非常有用,特别是$$ haskey Using Track-By With ngRepeat In AngularJS 1.2 by Ben Nadal打交道时。
问题是你每次都创建一个新的数组,所以这是角度需要跟踪的新东西。据我所知,ng-repeat
运行,然后立即再次检查其集合,看看在该周期中是否有任何改变。因为该函数返回一个新的数组,这被视为一个变化。
查看结果:http://jsfiddle.net/kL5YZ/。 如果您查看console.log
并单击该按钮,则会看到每次运行ng-repeat时,对象的$$hashKey
属性都将被更改。
更改从版本1.1.4开始,但更改日志没有给出任何线索,为什么行为不同。新的行为确实对我更有意义。
这里有一个伟大的职位,我发现解释了当前行为深入:How to Loop through items returned by a function with ng-repeat?
如果你一定要每次都返回相同的对象/数组,你不会有错误。你可以让函数缓存它根据参数创建的任何东西,并且当传入这些参数时总是返回相同的数组/对象。所以,myFunc('foo')将总是返回相同的数组,而不是一个新的相同。请参阅下面我的代码中的注释。 Live demo (click).
<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;
});
的
来源
2014-01-05 12:15:02
m59
可能重复[如何通过与NG-重复的函数返回的项目环路?(http://stackoverflow.com/questions/ 12336897/how-to-loop-through-items-by-a-function-with-ng-repeat) – m59