$q example
HTML
<script src="http://code.angularjs.org/1.0.0rc10/angular-1.0.0rc10.js"></script>
<div ng-controller="PrefsCtrl">
<p>Preferences:</p>
<p>{{prefs.history.length}} items in history:</p>
<span ng-repeat="item in prefs.history">
{{$index + 1}}. {{item}} <span ng-hide="$last">|</span>
</span><br>
<input type='text' ng-model='newHistoryItem'>
<button ng-click="addToHistory(newHistoryItem)">Add to history</button>
<br>
<br>
<p>async test: {{asyncTest}}</p>
<br>
<br>
<p>sync test: {{syncTest}}</p>
</div>
JavaScript
var app = angular.module('myApp', []);
app.service('testService', function($rootScope) {
this.prefs = {
faveColor: "Green",
rememberMe: true,
history: ['history one', 'history two', 'history three'],
popIt: function() {
alert('fave color: ' + this.faveColor);
}
};
this.fail = function() {
throw 'some really bad error happened';
};
});
function PrefsCtrl($scope, $q, testService) {
$scope.prefs = testService.prefs;
$scope.newHistoryItem = '';
$scope.addToHistory = function(newItem) {
$scope.prefs.history.push(newItem);
$scope.newHistoryItem = '';
};
function asyncAddItem(newItem) {
var deferred = $q.defer();
$scope.$apply(function() {
try {
//deferred.resolve(testService.fail());
deferred.resolve($scope.prefs.history.push(newItem));
}
catch (err) {
deferred.reject(err);
}
});
return deferred.promise;
};
function syncAddItem(newItem) {
$scope.prefs.history.push(newItem);
return newItem;
};
$scope.asyncTest = 'loading async... please wait';
var promise = asyncAddItem('async');
promise.then(
function(response) {
$scope.asyncTest = response; //success
}, function(reason) {
$scope.asyncTest = reason; //error
}
);
$scope.syncTest = syncAddItem('sync');
};