为什么这个控制器函数不止一次被调用

时间:2015-10-05 16:27:27

标签: angularjs

下面的代码(也在Plunker中)。在控制台上,我看到多个foo被打印出来。

<html>
  <head>
    <script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js'></script>
  </head>
  <body>
    <div ng-app='theApp'>
      <div ng-controller='TheController as ctl'>
        {{ctl.foo()}}
      </div>
    </div>
    <script>
     angular.module('theApp', [])
            .controller('TheController', [function() {
              this.foo = function() {
                console.log('foo');
              };
            }]);
    </script>
  </body>
</html>

1 个答案:

答案 0 :(得分:1)

由于视图表达式是函数调用的结果,因此监视器侦听器将多次调用它以检测函数结果是否稳定。为了进行比较,请参阅此fork of the example code,并注意函数foo仅被调用一次。

<html>
  <head>
    <script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js'></script>
  </head>
  <body>
    <div ng-app='theApp'>
      <div ng-controller='TheController as ctl'>
        {{ctl.bar}}
      </div>
    </div>
    <script>
     angular.module('theApp', [])
            .controller('TheController', [function() {
              this.foo = function() {
                console.log('foo');
                return "foo";
              };
              this.bar = this.foo();
            }]);
    </script>
  </body>
</html>