angular service example with promises
http://angularjs.org/
by jacobwsmith
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<div ng-controller="myCtrl">
<form name="myForm">
<label>Email address
<input type="email" ng-model="data.email" name="myEmail" ng-minlength="5" ng-maxlength="100" required />{{data.email}}</label>
</form>
</div>
JavaScript
// app
var app = angular.module('app', []);
// controller
angular.module('app').controller('myCtrl', function ($scope, DataService) {
// promise
var promise = DataService.get();
promise.then(function (obj) {
console.log('promise complete');
console.log(DataService.data);
$scope.data = obj;
}, function (reason) {
alert('Failed: ' + reason);
});
//
$scope.$watch('data', function (newValue, oldValue) {
console.log(newValue);
console.log($scope.data);
console.log(DataService.data);
},true);
});
// service
angular.module('app').service('DataService', function ($rootScope, $q) {
this.data = {
email: '[email protected]'
};
this.get = function () {
// perform some asynchronous operation,
// resolve or reject the promise when appropriate.
return $q(function (resolve, reject) {
var self = this;
setTimeout(function () {
if(true){
self.data = {email: '[email protected]'};
resolve(self.data);
} else {
reject('Error');
}
}, 1000);
});
}
});