Angular controller lifecycle

I have this angular controller

angular.module('partherApp')
  .controller('MyCtrl', function ($scope) {
    $scope.logToConsole = function() {
      console.log('Here I am.');
    };
});

      

and this view:

<div ng-controller="MyCtrl">
    {{logToConsole()}}
</div>

      

When the app opens in the browser, I see that I am getting a tree 'Here I am.'

. I expected to receive it once. Any ideas why this is happening?

+3


source to share


1 answer


The behavior in AngularJS directive, {{}}

(interpolation) is expected to get called every digest cycle and evaluate its expression. Like the interpolation directive, most angular directives are evaluated when starting the dataset loop. ng-bind

, ng-show

, ng-class

, ng-if

, Etc.

If you only want to execute the binding code once, you need to use the bindonce directive, which ::

and your code will be



<div ng-controller="MyCtrl">
    {{::logToConsole()}}
</div>

      

Detailed Explanation How does binding work in Angularjs?

+3


source







All Articles