为什么 ng-style 函数应用了两次? [英] Why is ng-style function applied twice?
问题描述
我有一个 Angular 应用,例如:
angular.module('ngStyleApp', []).controller('testCtrl', function($scope) {$scope.list = [1,2,3];$scope.getStyles = 函数(索引){console.log('获取索引的样式' + index);返回 {红色'};};});
带有相应的标记:
<ul ng-controller="testCtrl"><li ng-repeat="列表中的值" ng-style="getStyles($index)">{{价值}}
正如预期的那样,可见输出是三个红色列表项.但是该语句总共记录到控制台 6 次,这意味着视图渲染了两次:
获取索引 0 的样式获取索引 1 的样式获取索引 2 的样式获取索引 0 的样式获取索引 1 的样式获取索引 2 的样式
为什么?
实际上,试试 StackOverflow 中的这句话,它说得很好:
<块引用>当被监视的函数被评估时(在 $digest 期间),如果它们中的任何一个从之前的 $digest 发生了变化,那么 Angular 就会知道这个变化可能会波及其他被监视的函数(也许被改变的变量被用于另一个被监视的函数).因此,每个手表都会重新评估(也称为脏处理),直到没有手表导致更改.因此,通常您会看到每个摘要有 2 次调用被监视的函数,有时甚至更多(最多 10 次 - 在 10 次循环中放弃并报告错误,说它无法稳定).
(参考 此处)
I've got an angular app like:
angular.module('ngStyleApp', []) .controller('testCtrl', function($scope) { $scope.list = [1,2,3]; $scope.getStyles = function(index) { console.log('getting styles for index ' + index); return { color: 'red' }; }; });
with the corresponding markup:
<div ng-app="ngStyleApp"> <ul ng-controller="testCtrl"> <li ng-repeat="value in list" ng-style="getStyles($index)"> {{value}} </li> </ul> </div>
The visible output is three red list items, as expected. But the statement is logged to the console a total of 6 times, implying that the view is rendered twice:
getting styles for index 0 getting styles for index 1 getting styles for index 2 getting styles for index 0 getting styles for index 1 getting styles for index 2
Why?
解决方案The Angular
$digest
cycle evaluates the ngStyle attribute at least twice - once to get the value and once to check if it has changed. It actually keeps iterating until the value settles so could potentially check the value many times.Here's a picture to illustrate this:
Here is a good blog post illustrating this: angular digest blog
Actually, try this quote from StackOverflow that says it very well:
When watched functions are evaluated (during $digest) if any of them have changed from the previous $digest then Angular knows that change might ripple through to other watched functions (perhaps the changed variable is used in another watched function). So every watch is re-evaluated (also called dirty processing) until none of the watches results in a change. Thus typically you'll see 2 calls to watched functions per digest and sometimes more (up to 10- at 10 loops through it gives up and reports an error saying it can't stabilize).
(Reference here)
这篇关于为什么 ng-style 函数应用了两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!