Ng风格的函数不止一次被调用

问题描述 投票:0回答:2

In this plunk我有一个边界宽度的div,由输入字段中的值决定。我用含有ng-style函数的getBorder()实现了这一点。

我的问题是,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
2个回答
1
投票

这是因为AngularJS中的digest cycles

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

ngModel是注册观察者的指令之一。所以,你遇到的问题并不是真正的问题,因为ng-style试图使用getBorder()来获取价值。


0
投票

我希望这个解决方案能解决你的问题

   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>
© www.soinside.com 2019 - 2024. All rights reserved.