title: AngularJS: Using Shared Service(with $resource) to share data between controllers, but how to define callback functions?
body: <p>Note: I also posted this question on the AngularJS mailing list here: <a href="https://groups.google.com/forum/#!topic/angular/UC8_pZsdn2U" rel="noreferrer">https://groups.google.com/forum/#!topic/angular/UC8_pZsdn2U</a></p>
  
  <p>Hi All,</p>
  
  <p>I'm building my first AngularJS app and am not very familiar with Javascript to begin with so any guidance will be much appreciated :)</p>
  
  <p>My App has two controllers, ClientController and CountryController. In CountryController, I'm retrieving a list of countries from a CountryService that uses the $resource object. This works fine, but I want to be able to share the list of countries with the ClientController. After some research, I read that I should use the CountryService to store the data and inject that service into both controllers.</p>
  
  <p>This was the code I had before:</p>
  
  <p>CountryService:</p>
  
  <pre><code>services.factory('CountryService', function($resource) {
      return $resource('http://localhost:port/restwrapper/client.json', {port: ':8080'});
  });
  </code></pre>
  
  <p>CountryController:</p>
  
  <pre><code>//Get list of countries         
  //inherently async query using deferred promise
  $scope.countries = CountryService.query(function(result){       
          //preselected first entry as default
      $scope.selected.country = $scope.countries[0];  
  });
  </code></pre>
  
  <p>And after my changes, they look like this:</p>
  
  <p>CountryService:</p>
  
  <pre><code>services.factory('CountryService', function($resource) {
      var countryService = {};
  
      var data;
      var resource = $resource('http://localhost:port/restwrapper/country.json', {port: ':8080'});
  
      var countries = function() {
          data = resource.query();
          return data;
      }
  
      return {
          getCountries: function() {
              if(data) {
                  console.log("returning cached data");
                  return data;
              } else {
                  console.log("getting countries from server");
                  return countries(); 
              }
  
          }
      };
    });
  </code></pre>
  
  <p>CountryController:</p>
  
  <pre><code>$scope.countries = CountryService.getCountries(function(result){
          console.log("i need a callback function here...");
  });
  </code></pre>
  
  <hr>
  
  <p>The problem is that I used to be able to use the callback function in $resource.query() to preselect a default selection, but now that I've moved the query() call to within my CountryService, I seemed to have lost what.</p>
  
  <p>What's the best way to go about solving this problem?</p>
  
  <p>Thanks for your help,
  Shaun</p>