title: How do I let my controller know of the status of loading data?
body: <p>I'm working on a large AngularJS app in which I am trying to encapsulate all my Ajax code into various services which the controllers get data from. The problem revolves around needing to know the status of any ajax calls and displaying the correct information to the user. There could be no data found, data currently loading, or an error that has occurred preventing data from being loaded. The user needs to be shown a loading message, a "no data found" message, or an error message.</p>
  
  <p>Let's say I have a <code>ProjectService</code>. Ideally if there was a method called <code>getAllProjects</code> it would return an array of projects. But that way I have no idea what is happening with the server communication. </p>
  
  <p>So how to I let the controller know if data is loaded, loading, or an error has occurred? The best way I can come up with is using callbacks like in the pseudo code below. Is there any better way to accomplish such a thing or anything I may be overlooking? </p>
  
  <p>Thanks.</p>
  
  <pre class="lang-js prettyprint-override"><code>app.controller( "ProjectController", function( $scope, ProjectService ){
  
    // Set the initial / default status
    $scope.loadStatus = "loading";
  
    // Return an empty array initially that will be filled with
    // any data that is returned from the server
    // The callback function will be executed when the ajax call is finished
    $scope.projects = ProjectService.getProjects(function( status ){
  
      // Alert the controller of a status change
      setStatus( status );
  
    });
  
    function setStatus( ){
      $scope.loadStatus = status;
  
      // ... update the view or whatever is needed when the status changes....
    }
  
  });
  
  app.service( "ProjectService", function( $resource ){
  
    return {
      getAllProjects: function(){
  
        // ... load and return the data from the server ...
  
      }
    };
  
  });
  </code></pre>