angularjs - 为什么这个 Controller 函数被调用不止一次

标签 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>

最佳答案

由于您的 View 表达式是函数调用的结果,因此监视监听器将多次调用它以检测函数结果是否稳定。为了比较,请参阅此 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>

关于angularjs - 为什么这个 Controller 函数被调用不止一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32953371/

相关文章:

angularjs - 如何在 AngularJS 中创建任何类型的不可变提供者

javascript - 如何让 Controller 函数在 AngularJS 中只执行一次?

javascript - Angular.js 在 Controller 中调用指令函数

javascript - AngularFire 取消 AngularJS 数组中的项目

javascript - 以前在 Angular 矩js

javascript - $注入(inject)器:modulerr Failed to instantiate module bookApp due to: ReferenceError: 'when' is undefined at Anonymous function

angularjs - Ng 显示变量是否为数字

angularjs - 监听 $scope 上的多个事件

angularjs - 如何在 Angular Material 的 md-autocomplete 组件中禁止自由文本?

javascript - 字母值是否输入到 ng-model 保存的数字输入中?