I am doing a project in angularjs (1.x). My requirement is that I need to count the number of seconds elapsed.
For that, I have written a code using $interval service in my controller which is working perfectly fine.
Now , since this code is shared by many objects, so I thought to make it singleton. How can we do so?
Below is my code inside controller:
scope.timeDiff = 0;
var intervalId = $interval(function(){
scope.timeDiff += 1000;
},1000);
scope.$on('$destroy',function(){
$interval.clear(intervalId);
});
I have tried to create a service of timer like this:
angular.module('myModule').factory('customTimer', ['$interval','$rootScope',
function ($interval,$rootScope) {
var timerId, defaultInterval = 1000;
return {
startTimer: function (timeDiff) {
$interval(function(){
timeDiff += 1000;
},1000);
return timeDiff;
}
};
}]);
And then I try to call this service in my controller like this:
scope.timeDiff = customTimer.startTimer( scope.timeDiff);
console.log( "new timediff:",scope.timeDiff );
While timeDiff is updating in my timer service, but controller is always getting 0. What could be the reason?
timeDiff. It will return immediately. when you calledstartTimerfunction. It will not wait till 1 sec.