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

时间:2017-12-20 14:13:34

标签: angularjs

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

});

2 个答案:

答案 0 :(得分:1)

这是因为AngularJS中的digest cycles

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

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

答案 1 :(得分:0)

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

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

相关问题