ng-repeat的列表源调用了太多次

时间:2022-05-10 23:56:30

angular.module('NGTest', [
])
.controller('ItemList', ['$scope', function($scope) {
	console.log("ItemList controller init");
	var self = this;
  self.count = 4;
  self.getItems = function() {
  	console.log("ItemList.getItems() called");
	  return [];
  }
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="NGTest">
<div ng-controller="ItemList as lst">
<select ng-options="value for value in [1,2,3,4,5]" ng-model="lst.count"></select>
<div ng-repeat="item in lst.getItems()">foo </div>
</div>
</div>

By log entries, you can see that at startup, the lst.getItems() function is called twice. Why twice?

通过日志条目,您可以看到在启动时,lst.getItems()函数被调用两次。为什么两次?

It is also called when you change the value of lst.count, that is not used at all. Ok, I understand that AngularJS can not be that smart and see that the code of lst.getItems() does not depend on lst.count, but I'd expect that by default it assumes it does not and I have to feed it in function parameters.

更改lst.count的值时也会调用它,而根本不使用它。好吧,我明白AngularJS不是那么聪明,并且看到lst.getItems()的代码不依赖于lst.count,但我希望默认情况下它假定它没有,我必须将它提供给它功能参数。

1 个解决方案

#1


2  

Why twice

You will need to read up on how angular digest cycles work. Each cycle will run a minimum of 2 digests and more if scope changes within those digests.

您需要了解角度消化循环的工作原理。如果这些摘要中的范围发生变化,每个周期将至少运行2个摘要和更多。

Using a function as source in view for ng-repeat is not a good idea. Get your data in controller and pass to view as scope array

在ng-repeat视图中使用函数作为源不是一个好主意。在控制器中获取数据并传递给作为范围数组的视图

self.items= getItems();   

function getItems(){
   console.log("ItemList.getItems() called");
   return [];
}

Now the function will only be called once...when controller initializes

现在该函数只会被调用一次......当控制器初始化时

View

<div ng-repeat="item in lst.items">{{item}}</div>

#1


2  

Why twice

You will need to read up on how angular digest cycles work. Each cycle will run a minimum of 2 digests and more if scope changes within those digests.

您需要了解角度消化循环的工作原理。如果这些摘要中的范围发生变化,每个周期将至少运行2个摘要和更多。

Using a function as source in view for ng-repeat is not a good idea. Get your data in controller and pass to view as scope array

在ng-repeat视图中使用函数作为源不是一个好主意。在控制器中获取数据并传递给作为范围数组的视图

self.items= getItems();   

function getItems(){
   console.log("ItemList.getItems() called");
   return [];
}

Now the function will only be called once...when controller initializes

现在该函数只会被调用一次......当控制器初始化时

View

<div ng-repeat="item in lst.items">{{item}}</div>