title: Coordinating multiple AJAX calls in Angular using Restangular
body: <p>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?</p>
  
  <p>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. </p>
  
  <pre><code>&lt;div ng-controller="MyCtrl"&gt;
      &lt;div ng-if="state.isLoading" class="loading-animation"&gt;&lt;/div&gt;
      &lt;div ng-if="!state.isLoading"&gt;
          &lt;span ng-bind-template="Property: {{model.property}}"&gt;&lt;/span&gt;
          &lt;button ng-click="refresh()"&gt;Refresh&lt;/button&gt;
      &lt;/div&gt;    
  &lt;/div&gt;
  </code></pre>
  
  <pre class="lang-js prettyprint-override"><code>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();
  }]);
  </code></pre>
  
  <p>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.</p>