$timeout is calling services twice


#1

Hi,

I am using Ionic 1 (which appears to be using AngularJS 1.5.3). I was facing a strange issue while testing my app using Ripple emulator on Google Chrome, my service method was being called twice. After debugging for sometime, I was able to narrow down it to $timeout.

In my controller, I am using a $timeout method to invoke a method defined in controller like below (this is default tab example of Angular, in which I can replicate the same issue, so I am sharing code of that):

Controller

angular.module('starter.controllers', [])

.controller('DashCtrl', function($scope, $timeout, PrintService) {
    $scope.myName = "devilzk";
    $scope.counter = 0;
    
    $timeout(function(){
        console.log("ABC");
        PrintService.printMessage("why");
        $scope.counter++;
    }, 2000);
})

Services

    angular.module('starter.services', [])

    .service('PrintService', function(){
        this.printMessage = function(message){
          console.log("Printing via Service:: " + message);
        };
    })

In templates > tab-dash.html file, I specified following HTML snippet:

<h2>Welcome to Ionic</h2>
<h1>{{ myName }}</h1>
<h3>{{ counter }}</h3>

Now when I run this code in Ripple, counter value is updated only one time as expected after 2 seconds, and I see it being displayed as 1.

However, in console log, my service message is being displayed twice as well console.log(). I tried to replicate same in simple AngularJS app, but it worked fine there.

Lastly, in several attempts, I found that if I don’t use ng-app directive on html tab in index.html, but instead use AngularJS’s bootstrap method to create my app like:

document.addEventListener('deviceReady', function(){
      angular.bootstrap(document, ['starter']);
}, false);

Then $timeout was triggered only once. So little confused, because most of ionic examples are not using angular’s bootstraping approach. Secondly, with ng-app approach, why counter value was incremented only once, but console log appeared twice (i.e. service method was called twice).