$timeout example
by forivall
HTML
<script src="http://code.angularjs.org/1.1.4/angular.js"></script>
<div ng-controller="TimerCtrl">
<h1>1-second ticks since page load:</h1>
<h2>{{tickModel.ticks}} ticks</h2>
<h2>{{tockModel.tocks}} tocks</h2>
</div>
JavaScript
var app = angular.module('myApp', []);
app.factory(
'tickService', ['$q', '$timeout', function ($q, $timeout) {
function getClockPromise(scope) {
var tickHandle = $q.defer();
var tickModel = tickHandle.promise;
console.log('Constructing tick service');
var nextTick = function () {
// Instead of relying on being able to get a new promise, re-use the change
// observation features of the initial (now resolved) promise. As in the
// Tock service, read previous state using a then handler, but instead of
// creating a new promise to return value+1, perform assignment through the
// promise's $$v model. Any scopes using the promise as a model will have
// their data binding refreshed.
tickModel.then(function (data) {
tickModel.$$v.ticks = data.ticks + 1;
});
// Repeat this every two seconds.
$timeout(nextTick, 1000);
console.log('Scheduled next tick.');
};
// One-time resolve to prime the engine at t0.
tickHandle.resolve({
ticks: 0
});
// Schedule a delayed callback to simulate a service that is gated on
// a remote service before resolving a pending promise for a calculation
// derived from that remote service's data.
$timeout(nextTick, 1000);
console.log('Scheduled first tick.');
return tickModel;
}
// Wire the function to object interface and return the service.
this.getClockPromise = getClockPromise;
return this;
}]).factory(
'tockService', ['$q', '$timeout', function ($q, $timeout) {
function getClockPromise() {
console.log('Constructing tock service');
// 1) Create and immediately resolve a promise for t0.
// 2) Create and leave unresolved a promise for t1.
var handleToResolve = $q.defer();
var tockHandle =...