【问题标题】:Ng-style function called more than once多次调用 Ng 风格的函数
【发布时间】:2017-12-20 14:13:33
【问题描述】:

In this plunk 我有一个 div,其边框宽度由输入字段中的值确定。我通过包含getBorder() 函数的ng-style 来实现这一点。

我的问题是 getBorder() 被调用两次,有时是三次,而不是一次。为什么会发生这种情况以及如何解决?

HTML

    Width: <input type="number" ng-model="borderWidth"/>
    <br/>
    <div style="background-color:orange;height:200px;width:100px" 
         ng-style="{ 'border': getBorder() }"></div>

JavaScript

var app = angular.module('app', []);

app.controller('ctl', function ($scope) {

    $scope.getBorder = function(){
      alert('getBorder called');
      return $scope.borderWidth + 'px solid black';
    };

});

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    这是因为 AngularJS 中的 digest cycles

    AngularJS 注册观察者来观察范围内的变化,一旦发生变化,它会使用摘要循环刷新相应视图/模型之间的绑定。这就是您可以在数据和屏幕上看到实时变化的原因。

    ngModel 是注册观察者的指令之一。因此,您遇到的问题并不是真正的问题,因为 ng-style 正在尝试使用 getBorder() 获取值。

    【讨论】:

    • 对性能有影响吗?当我的应用程序启动时,getBorder() 函数被调用了 80 次以上,可能每次都因为任何原因出现循环时被调用。
    • @ps0604 -- 每次绑定更改时都会调用该函数,即在您的情况下,每当ng-model 的值发生更改时。这是 AngularJS 可以做这些事情的唯一方法。就性能而言,是的,如果您有数百个这样的观察者,您可能会注意到浏览器出现延迟。但是只有一个观察者并没有那么大的影响。
    【解决方案2】:

    我希望这个解决方案可以解决您的问题

       var app = angular.module('app', []);
    
        app.controller('ctl', function ($scope) {
            $scope.borderWidth = 1;
    
            $scope.$watch('borderWidth', function (newVal, oldVal) {
            console.log()
              if (angular.isDefined(newVal)) {
                $scope.styleBorder = newVal + 'px solid black';
              }
            });
        });
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
        <html ng-app="app">
          <body>
            <div ng-controller="ctl">
                Width: <input type="number" ng-model="borderWidth"/>
                <br/>
                <div
                  style="background-color:orange;height:200px;width:100px;"
                  ng-style='{"border": styleBorder}'
                ></div>
            </div>
          </body>
        </html>

    【讨论】:

    • 这有点类似于代码中的ng-model。手动注册观察者并不能解决这个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-26
    • 2016-11-07
    • 2012-08-08
    • 2023-03-23
    • 2017-06-12
    • 2018-04-14
    相关资源
    最近更新 更多