1

I am writing something in angular (still learning), and found that while im firing method i see duplicated results. I have prepared very simple code to simulate this index.html:


    
      {{show()}}
    

(function(){
    var app = angular.module('test', []);

    app.controller('testController', ['$scope', function($scope){
        $scope.show = function(){
            console.log('test');
        };
    }]);
})();

And in chrome console I can see 'test' shown 3 times.. Why is it happening? Got this issue in other scripts i wrote, sometimes shown twice, what i am doing wrong? Could anyone please tell me? Thanks

johny_q
  • 79
  • 3
  • @johny_q Are you sure you don't have any additional console.log left somewhere else? Another tip: if you comment out the one `console.log()` you're mentioning, are there 0 or 2 "test"s in the console? – developer10 Oct 07 '14 at 12:57
  • 1
    possible duplicate of [Why angularjs will invoke function \`name()\` twice?](http://stackoverflow.com/questions/14973792/why-angularjs-will-invoke-function-name-twice) – Blackunknown Oct 07 '14 at 13:04
  • {{show()}}
    – johny_q Oct 07 '14 at 14:47

2 Answers2

2

What you are seeing is the result of Angular's $digest cycle.

https://docs.angularjs.org/api/ng/type/$rootScope.Scope

From the Angular docs...

$digest(); Processes all of the watchers of the current scope and its children. Because a watcher's listener can change the model, the $digest() keeps calling the watchers until no more listeners are firing. This means that it is possible to get into an infinite loop. This function will throw 'Maximum iteration limit exceeded.' if the number of iterations exceeds 10.

Each $digest will evaluate all watchers, which in your case means calling your function each time.

If you are exceedingly curious about how this happens then place a breakpoint on the $digest function in the Angularjs source and you will see your function called as part of that cycle. Basically enters a do-while loop and executes your function until its internal logic is satisfied that no more digest cycles are needed. For the simple case as demonstrated by your code, that was exactly three times.

The condensed version of the above cycle is that your function is executed once to initialize the watch value within the $digest cycle. It is then evaluated in a loop of the cycle to see if anything has changed, which results in a second call to your function. Finally a third execution occurs at which time if the value has not changed the $digest logic is satisfied that we can end our loop.

mccainz
  • 3,478
  • 5
  • 35
  • 45
-1

How about you use it in your HTML like this:

{{show}}
developer10
  • 1,450
  • 2
  • 15
  • 31