7

的阵列AngularJS InfDig错误(无限循环)与NG-复读功能这里是我的代码:返回对象

<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

你能解释这种情况呢?非常感谢。

+0

可能重复[如何通过与NG-重复的函数返回的项目环路?(http://stackoverflow.com/questions/ 12336897/how-to-loop-through-items-by-a-function-with-ng-repeat) – m59

回答

10

作为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; 
}); 
+0

谢谢。但是如果我需要将参数传递给这个函数呢: '

something

' – user3162402

+0

@ user3162402我用一个通用但完整的解决方案更新了我的答案。我还发现了一篇关于ng-repeat与函数一起工作的非常好的帖子,但我仍然不知道它为什么会用到它。 – m59

+0

谢谢!答应给我工作! :) –