2015-10-05 80 views
3

下面的代碼(也在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

由於您的視圖表達式是函數調用的結果,因此監聽器將多次調用它以檢測函數結果是否穩定。作爲比較,請參見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> 
相關問題