You could either build a special services for that which can be injected everywhere where it is needed or you just put it on $rootScope
. Normally you should avoid putting things on the $rootScope
as global state is often a code smell. However, if that's really what you need in your case, then this might suite your needs.
You can simply put that code on a run
block so it get's executed as soon as the module is loaded.
myModule.run(['$rootScope', function($rootScope){
setInterval(function(){
$rootScope.now = new Date().getTime();
}, 1000)
}]}
Be aware that in the fashion I wrote the code above, Angular won't be notified about that change. However, notifying Angular every second about that change might not be what your want as it could lead to serious performance problems. Just to clarify things: If you do want Angular to be notified about the change and update all bindings, then the variable update would need to be wrapped in a $apply
call.
myModule.run(['$rootScope', function($rootScope){
setInterval(function(){
$rootScope.$apply(function(){
$rootScope.now = new Date().getTime();
});
}, 1000)
}]}
Also be aware that most of the time you want to avoid setInterval
as the time between the processing can be non deterministic. Most of the time setTimeout
is better suited. It's out of the scope of this answer to dive into that but if you want to read up on that topic I recommend reading John Resig's post on the topic: http://ejohn.org/blog/how-javascript-timers-work/