I am trying to use an ajax spinner while a function works but I don't know how to tell the spinner to hide when the function is done.
The code works like so:
- Click a button, the spinner appears and a function in the controller is fired to update some data.
- That function accesses a service that uses $resource to update the data
- Can't hide the spinner as I don't know when the process ha completed.
So, how do I know when the whole thing is complete so I can quit showing the spinner?
Clicking a button in the view triggers updateData()
. In my controller I have:
$scope.updateData = function () {
Data.updateData();
}
The updateData method of the Data service referenced in the above is:
updateData : function() {
API.update({
uri : 'updateData'
}, {
data : data
}, function(data) {
data = data[0];
$rootScope.$emit('Data.updateSuccess');
}, function(err) {
$rootScope.$emit('Data.updateError', err);
});
That API comes from a factory that extends $resource:
.factory('API', ['$resource', function($resource){
return $resource('/location/:uri', {}, {
query : {
method : 'GET',
isArray : true
},
update: {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
},
create: {
method: 'POST',
isArray : true,
headers: {
'Content-Type': 'application/json'
}
}
});
}]);
}
At first I thought I could listen for those $emits (I also tried $broadcast) in the controller with
$rootScope.$on('Data.updateSuccess', $log.log('update success'));
$rootScope.$on('Data.updateError', $log.log('update failure'));
but when I do I get both of them every time. So what do I need to do to determine when to hide my ajax spinner at the completion of this update process?