ngRepeat里面的函数执行得太频繁了 [英] function inside ngRepeat executed too often
问题描述
我有三个标签
在 ng-include
中有不同的html。这些选项卡使用 ng-repeat
显示。只有一个HTML模板包含函数调用,但它执行了3次(每次 ng-repeat
迭代一次)。这里有什么问题以及如何解决?
I have three tabs
that has different html inside ng-include
. These tabs are shown using ng-repeat
. Only one HTML template contains function call, but it's executed 3 times (once per ng-repeat
iteration). What is wrong here and how to fix it?
var app = angular.module('myApp', [])
app.controller('myCtrl', [
'$scope',
function($scope){
$scope.randomFnc = function (i) {
console.log(i);
return "Placeholder text";
}
$scope.tabs = [
"a",
"b",
"c"
];
}
])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="myCtrl">
<div ng-repeat="tab in tabs">
<div ng-if="$index == 1">
{{$index}}<input type="text" value="" placeholder="{{randomFnc($index)}}"/>
</div>
<div ng-if="$index != 1">{{$index}}</div>
</div>
</div>
</div>
推荐答案
您可以使用 ng-init
,但强烈建议不要这样做。你的函数调用被执行三次的原因是因为angular不知道在每个摘要周期中是否有任何 $ scope
值发生了变化。因此,将为每个摘要周期执行该函数。在您的情况下,当 ng-if
条件变为真时以及在两个摘要周期中共计三个时,它将被执行。这就是为什么它与值1一起被执行3次而不管数组中的项数是多少。
You can use ng-init
though it is not highly recommended to achieve this. The reason why your function call is being executed thrice is because angular doesn't know if any $scope
value has changed during each digest cycle. So the function will get executed for each digest cycles. In your case, it will get executed when the ng-if
conditions become true as well as during the two digest cycles accounting a total of three. This is the reason why it gets executed 3 times with the value 1 regardless of the number of items in the array.
var app = angular.module('myApp', [])
app.controller('myCtrl', [
'$scope',
function($scope) {
$scope.x = {};
$scope.randomFnc = function() {
console.log("once");
$scope.placeholderText = "Placeholder text";
}
$scope.tabs = [
"a",
"b",
"c"
];
}
])
app.directive('trackDigests', function trackDigests($rootScope) {
function link($scope, $element, $attrs) {
var count = 0;
function countDigests() {
count++;
$element[0].innerHTML = '$digests: ' + count;
}
$rootScope.$watch(countDigests);
}
return {
restrict: 'EA',
link: link
};
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="myCtrl">
<div ng-repeat="tab in tabs">
<div ng-if="$index == 1" ng-init="randomFnc()">
{{$index}}<input type="text" value="" placeholder="{{placeholderText}}" />
</div>
<div ng-if="$index != 1">{{$index}}</div>
</div>
</div>
<track-digests></track-digests>
</div>
这篇关于ngRepeat里面的函数执行得太频繁了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!