title: Count pending $q promises in angularjs
body: <p>I'm working on a complex angularjs app. Complex meaning single view can have several different data sources being queried from different places of the code, e.g. page-part controller or directive controller. Sometimes some of these requests can take longer time to resolve, thus leaving the view in somewhat invalid state.
  I would like to be able to display some sort of "data loading" banner and disable user interaction with view until all promises have resolved. This works with simple screens using $q.all() function.
  But, the way app is being structured is more business logic centric, rather than data-source centric. So for a more complicated screen there will be no single place where all promises made are naturally accessible. Creating such a place in the code seems cumbersome.</p>
  
  <p>I have come up with this solution:</p>
  
  <pre><code>angular.module('myApp').service('qConfigurer', function ($q) {
      var pending = 0;
      var origDefer = $q.defer;
  
      $q.defer = function() {
          pending++;
          var result = origDefer.apply(arguments);
  
          var origResolve = result.resolve;
          var origReject = result.reject;
  
          result.resolve = function() {
              pending--;
              return origResolve.apply(arguments);
          };
  
          result.reject = function() {
              pending--;
              return origReject.apply(arguments);
          };
  
          return result;
      };
  
      $q.pending = function() {
          return pending;
      };
  
      return {};
  });
  </code></pre>
  
  <p>is there less <em>hacky</em> to achieve the same?</p>