3

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 application get's opened in the browser I can see that I get tree times 'Here I am.'. I'd expected to get it once. Any ideas why this happens?

Dag Høidahl
  • 7,873
  • 8
  • 53
  • 66
BetaRide
  • 16,207
  • 29
  • 99
  • 177
  • 2
    Angular digest cycle is running, to peform directly check, Angular can run this cycle many times during which it will evaluate your expression, – Chandermani May 14 '15 at 08:04

1 Answers1

3

It is expected behaviour in AngularJS, {{}}(interpolation) directive will get call on each digest cycle and evaluates there expression. Like interpolation directive most of the angular directive gets evaluated when digest cycle run eg. ng-bind, ng-show, ng-class, ng-if, etc.

If you want to execute you binding code only once then you need to use bindonce directive which :: & your code would be

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

Detailed explaination How Binding work in Angularjs?

Community
  • 1
  • 1
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
  • whats a digest cycle ? – eran otzap May 14 '15 at 08:12
  • @eranotzap digest cycle is update all the binding which are there on the view..which updates all the scope variable. http://stackoverflow.com/questions/12463902/how-does-the-binding-and-digesting-work-in-angularjs – Pankaj Parkar May 14 '15 at 08:14
  • does that mean that each change in the scope would trigger a digest cycle ? – eran otzap May 14 '15 at 08:54
  • @eranotzap no it will not run the digest cycle every time..It gets called whenever you are using any method which has wrapped in `$apply` function then only digest cycle run..take example of `ng-click` directive which whatecer you write it..angular will wrap that code inside `$apply` function..which call digest cycle.when code execution completed..same logic applies to `$http`, `$interval`, `$timeout`, etc. – Pankaj Parkar May 14 '15 at 09:15
  • does a digest occur for the entire document ? – eran otzap May 14 '15 at 10:29
  • 1
    @eranotzap AFAIK It depends..it will occur only for the angular context..if you applied angular app on body then yes..or if you applied angular app for particular div then that digest cycle will run in that scope only. :) – Pankaj Parkar May 14 '15 at 10:45