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

use*_*402 7 infinite-loop angularjs angularjs-ng-repeat angularjs-infdig

这是我的代码:

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

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

在Angular.js v.1.1.1中,没有错.在Angular.JS v 1.2.1中,我得到了一个infDig错误.

v.1.1.1的小提琴

v.1.2.1的小提琴

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

m59*_*m59 11

从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"}];
}
Run Code Online (Sandbox Code Playgroud)

下面的文章有助于更详细地理解表达式以及它为何如此有用,特别是在使用Ben Hasad在AngularJS 1.2中使用带有ngRepeat的 $$ haskey进行跟踪时.

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

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

此更改从版本1.1.4开始,但更改日志未提供有关行为不同的原因的任何线索.这种新行为对我来说更有意义.

这是一个很棒的帖子,我发现深入解释当前的行为:如何循环使用ng-repeat函数返回的项目?

如果确保每次都返回相同的对象/数组,则不会出现错误.您可以根据参数使函数缓存它创建的任何内容,并在传入这些参数时始终返回相同的数组/对象.因此,myFunc('foo')将始终返回相同的数组,而不是一个看起来相同的新数组相同.请参阅下面的代码中的注释.现场演示(点击).

<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>
Run Code Online (Sandbox Code Playgroud)

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;
});
Run Code Online (Sandbox Code Playgroud)