Angular.js看一个函数调用的结果 [英] Angular.js watching the result of a function call
问题描述
是否与下面的代码片段的任何表面上的问题:
Is there any ostensible issue with the following snippet:
<ul id="entry-name" class="breadcrumb">
<li ng-repeat="dir in pathElements()" class="active">
<span ng-show="!$last">
<a href="#!?path={{dir.url}}">{{ dir.name }}</a> <span ng-show="!$first" class="dividier">/</span>
</span>
</li>
<li class="active">{{ pathElements()[pathElements().length - 1].name }}</li>
</ul>
这个JS:
$scope.pathElements = function() {
var retval = [];
var arr = $scope.currentPath().split('/');
if (arr[0] == '') {
arr[0] = '/';
}
var url = "/";
retval.push({name: arr[0], url: url});
for (var i = 1; i < arr.length; ++i) {
if (arr[i] != '') {
url += arr[i] + '/';
retval.push({name: arr[i], url: url});
}
}
return retval;
};
这似乎是导致错误:!10 $摘要()迭代达到中止错误,但我不知道为什么。是不是因为pathElements()将返回每次一个新的数组?有没有办法来解决这个问题?
This seems to be causing a "Error: 10 $digest() iterations reached. Aborting!" error, but I'm not sure why. Is it because pathElements() is returning a new array each time? Is there a way to get around this?
推荐答案
是的,这是因为你每次都返回一个新的数组,$消化周期无限循环(但角停止它)。你应该声明它的函数之外。
Yes, this happens because you're returning a new array every time, and the $digest cycle loops infinitely (but Angular ceases it). You should declare it outside the function.
$scope.pathArray = [];
$scope.pathElements = function() {
// retval becomes $scope.pathArray
if (weNeedToRecalcAllPathVariables) {
$scope.pathArray.length = 0;
// ...
}
// ...
}
我们使用 $ scope.pathArray.length = 0
,而不是创建一个新的,以避免它不断地射击。
We use $scope.pathArray.length = 0
instead of creating a new one, to avoid it firing continuously.
您还应该考虑什么@Flek建议。调用该函数只有一次,在你需要它重新计算的时间。和所有你绑定应该是直接在 $ scope.pathArray
。
You should also consider what @Flek suggests. Call this function only once, in the time you need it to recalculate. And all you binds should be directly over $scope.pathArray
.
如果你需要一个函数使用它之前测试其clenaning状态,那至少我建议你创建两个单独的功能,只是为了让每个功能与它自己的属性。
If you do need a function to test its clenaning state before using it, then at least I suggest you to create two separate functions, just to keep each function with it own attribution.
这篇关于Angular.js看一个函数调用的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!