gpt4 book ai didi

AngularJS InfDig 错误(无限循环),ng-repeat 函数返回对象数组

转载 作者:行者123 更新时间:2023-12-03 00:03:33 25 4
gpt4 key购买 nike

这是我的代码:

<h1 ng-repeat="item in func()">something</h1>

$scope.func = function(){
return [{"property" : "value1"},{"property": "value2"}];
}

在 Angular.js v. 1.1.1 中没有错误。在 Angular.JS v 1.2.1 中,我遇到了 infDig 错误。

Fiddle of v.1.1.1

Fiddle of v.1.2.1

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

最佳答案

As of AngularJS 1.2: The "track by" expression was added to ng-repeat and more appropriately addresses this issue as demonstrated in the following code.

<h1 ng-repeat="item in func() track by $index">something</h1>

$scope.func = function(){
return [{"property" : "value1"},{"property": "value2"}];
}

The following article helps understand the expression in more detail and why it is so useful, particularly when dealing with $$haskey Using Track-By With ngRepeat In AngularJS 1.2 by Ben Nadal.

问题是您每次都创建一个新数组,因此 Angular 需要跟踪新的东西。据我所知,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;
});

关于AngularJS InfDig 错误(无限循环),ng-repeat 函数返回对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20933261/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com