为什么应用两次NG-风格的功能? [英] Why is ng-style function applied twice?

查看:80
本文介绍了为什么应用两次NG-风格的功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个角应用程式,例如:

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'
       };
   };
});

与相应的标记:

<div ng-app="ngStyleApp">
    <ul ng-controller="testCtrl">
        <li ng-repeat="value in list" ng-style="getStyles($index)">
            {{value}}
        </li>
    </ul>
</div>

可见输出为三红列表项,符合市场预期。但该语句被记录到控制台共6次,这意味着该视图显示了两次:

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

为什么?

  • JSFiddle

推荐答案

该角 $消化周期评估ngStyle属性至少两次 - 一次获得的价值,一旦检查它是否已经改变。它实际上一直迭代直到值平息这样可能会检查值很多倍。

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:

下面是说明这是一个很好的博客文章:
<一href=\"http://nathanleclaire.com/blog/2014/01/31/banging-your-head-against-an-angularjs-issue-try-this/\">angular消化博客

Here is a good blog post illustrating this: angular digest blog

其实,试着从计算器这句话,说非常好:

Actually, try this quote from StackOverflow that says it very well:

在观看功能评估($消化过程中)如果其中任何已从previous改变$消化再角知道这种改变可能是通过波及到其他监视功能(也许改变的变量在另一个观看功能使用)。所以每腕表重新评估(也叫脏处理),直到没有任何的改变手表的结果。因此,通常你会看到两个通话每消化功能看,有时多个(最多10圈10-通过它放弃并报告错误说,它不能稳定)。

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).

(参考<一个href=\"http://stackoverflow.com/questions/19993294/angular-scope-function-executed-twice-when-it-should-only-run-once\">here)

这篇关于为什么应用两次NG-风格的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆