var app = angular.module('plunker', []);
app.service('Service', function($q, $timeout) {
function methodWithPromise() {
var deferred = $q.defer();
setTimeout(function() {
// called multiple times
deferred.notify("10%");
deferred.notify("30%");
deferred.notify("70%");
deferred.notify("100%");
// deferred.reject(new Error());
deferred.resolve('YAY');
});
return deferred.promise;
}
return {
methodWithPromise: methodWithPromise
};
})
app.controller('MainCtrl', function($scope, Service) {
var count = 0;
$scope.$watch(function() {
console.log(++count);
});
console.clear();
function showResult(result) {
console.info('success:', result);
}
function showError(error) {
console.error('error:', error);
}
function finalize() {
console.log('finally!');
}
function showProgress(progressValue) {
console.info('progress:', progressValue);
}
Service.methodWithPromise()
.then(showResult, null, showProgress)
.catch (showError)
.finally(finalize);
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.2.x" src="https://code.angularjs.org/1.2.21/angular.js" data-semver="1.2.21"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl"></body>
</html>
/* Put your css in here */