加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 07:53:15 所属栏目:安全 来源:网络整理
导读:这是我的代码: 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 Fiddl
这是我的代码:
<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;
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读