Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is this controller function called more than once [duplicate]

Tags:

angularjs

Code below (also in Plunker). On the console I see multiple foos getting printed.

<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>
like image 708
Marcus Junius Brutus Avatar asked Jan 27 '26 14:01

Marcus Junius Brutus


1 Answers

Since your view expression is the result of a function call, the watch listener will invoke it multiple times to detect if the function result is stable. For comparison, see this fork of the example code, and note how the function foo is only called one time.

<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>
like image 193
mtadd Avatar answered Jan 30 '26 03:01

mtadd