SO Example of Deferral
Example of deferring a call to a service and using a "spinner" while fetching data
by Jeremy Likness
HTML
<div ng-app="myApp" ng-controller="myController">
<div ng-show="showSpinner">[[SPINNER]]</div>
<ul ng-repeat="number in stuff"><li>{{number}}</li></ul>
</div>
JavaScript
var app = angular.module("myApp", []);
app.service("myService", function($q, $timeout) {
var _this = this;
this.$q = $q;
this.$timeout = $timeout;
var stuff = [1, 2, 3];
return {
getStuff: function() {
var deferral = $q.defer();
_this.$timeout(function() {
deferral.resolve(stuff);
}, 2000);
return deferral.promise;
}
};
});
app.controller("myController", function($scope, myService) {
var _this = this;
this.$scope = $scope;
this.myService = myService;
this.$scope.showSpinner = true;
this.myService.getStuff().then(function(data) {
_this.$scope.stuff = data;
_this.$scope.showSpinner = false;
});
});