I have an Angular application with a view which gets updated via $scope references to some model and state object exposed by a factory singleton. During initialization, or under certain actions within the view, the factory must make multiple AJAX calls (using Restangular) and wait for all promises to be resolved before updating its state and model properties. How can I wait for multiple futures to be resolved before applying appropriate side-effects on the data returned from the future?
e.g. A div which shows either a loading spinner or a model property and a button to refresh this property depending on a state.
<div ng-controller="MyCtrl">
<div ng-if="state.isLoading" class="loading-animation"></div>
<div ng-if="!state.isLoading">
<span ng-bind-template="Property: {{model.property}}"></span>
<button ng-click="refresh()">Refresh</button>
</div>
</div>
App.controller('MyCtrl', ['$scope', 'MyFactory', function('$scope', 'Factory') {
$scope['model'] = Factory['model'];
$scope['state'] = Factory['state'];
$scope.refresh = function() {
Factory.init();
};
}])
.factory('MyFactory', ['restangular', function('Rest') {
var Factory = {
model = {
property: null
},
state = {
isLoading = false;
}
};
Factory.init = function() {
Factory['state']['isLoading'] = true;
var promise1 = Rest.one('first').get();
promise2 = Rest.one('second').get();
// Resolve both promises.
// Only when both promises are done,
// update model.property based on data returned and relevant logic.
// Toggle isLoading state when finalized.
}
return Factory;
}])
.run(['MyFactory', function(Factory) {
Factory.init();
}]);
What I'm having trouble with is how to implement the commented section in Factory.init(). I know I can use Angular's $q but I'm not very well versed in deferred objects and I find Angular's documentation on $q to be a bit confusing.