带有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 你能解释一下这种情况吗?非常感谢.
问题是你每次都在创建一个新的数组,所以这是一个角度需要跟踪的新东西.据我所知,ng-repeat运行,然后立即再次检查其集合,以查看该循环中是否有任何变化.因为该函数返回一个新数组,这被视为一个变化. 看看这个:http://jsfiddle.net/kL5YZ/. 更改从版本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; }); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |