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

前端之家收集整理的这篇文章主要介绍了带有ng-repeat函数的AngularJS InfDig错误(无限循环),返回对象数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是我的代码
<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.

06000

The following article helps understand the expression in more detail and why it is so useful,particularly when dealing with $$haskey 07000.

问题是你每次都在创建一个新的数组,所以这是一个角度需要跟踪的新东西.据我所知,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;
});
原文链接:https://www.f2er.com/angularjs/143439.html

猜你在找的Angularjs相关文章