I was trying the code given in angularjs docs (given here: http://jsfiddle.net/zGqB8/) It just implements a time factory and uses $timeout to update the time object after each second.
angular.module('timeApp', [])
.factory('time', function($timeout) {
var time = {};
(function tick () {
time.now = new Date().toString();
$timeout(tick, 1000); // how to do it using setInterval() ?
})();
return time;
});
How would I do it using setInterval() function instead of $timeout() ?
I know that one need to use scope.$apply()
to enter the angular execution context but how would that work in a factory function? I mean, in a controller, we have a scope, but we don't have scope in a factory function?
Latest release candidate (1.2.0 rc3) has interval support. See changelog
Could you call a normal JavaScript method and then within that method wrap the Angular code with an $apply?
Example
You can use
$timeout
as an interval.If the view is destroyed, you can destroy it with listening on
$destroy
:Update
Angular has implemented an $interval feature in version 1.2 - http://docs.angularjs.org/api/ng.$interval
Legacy example below, disregard unless you're using a version older than 1.2.
A setInterval implementation in Angular -
I've created a factory called timeFunctions, which exposes $setInterval and $clearInterval.
Note that any time I've needed to modify scope in a factory I've passed it in. I am unsure if this meets the "Angular way" of doing things, but it works well.
Example Usage: