Sumit Arora
Sumit Arora

Reputation: 5241

How come $timeout updates the $rootScope variables from service to controller in AngularJs

I have following service :

App.service('DateTimeService',function($timeout,$rootScope)
{
    var rootThis = this;
    this.countUp = function() {
        DateTime1 = new Date();
        console.log(DateTime1);
        $timeout(rootThis.countUp, 5000);

        $rootScope.DateTime = DateTime1;
    }    
    $timeout(rootThis.countUp, 5000); 

})

This has been injected to the Controller :

var aController = function($scope, $rootScope, $location, $http,DateTimeService)
{

}

I have defined the following in angularJs view :

<span id="datetime">{{DateTime}}</span>

Now when I run this program, this DateTime automatically get updated into the view, As $rootScope.DateTime automatically got updated in the DateTimeService on recursive call.

How come ?, However I tried and search many ways so that dynamically updated value of some $rootScope variables in a service can be updated in AngularJs Scope and then view ? ( but I didn't find any?), now when I run the function inside the DateTime Service by calling this : $timeout(rootThis.countUp, 5000); then it updates the value to the view ?

Upvotes: 1

Views: 789

Answers (1)

koox00
koox00

Reputation: 2731

$timeout actually calls $scope.$apply() when it finishes.
$scope.$apply() triggers a digest cycle,
since your DateTime is a $rootScope variable, it will get updated in the view in the digest cycle.

Upvotes: 2

Related Questions