title: How can I force this AngularJS service to wait until it has a value to return?
body: <p>I have a service that is called by multiple controllers. It loads data into an object <code>categories</code>:</p>
  
  <pre><code>.service('DataService', ['$http', '$q', function($http, $q) {
  
      var categories = {};
  
      // Return public API.
      return({
          setCategory: setCategory,
          getCategory: getCategory,
          getJSON: getJSON,
          categories: categories
      });
  
  
      function setCategory(name, category) {
          console.log("setting category");
          console.log(name, category)
          categories[name] = category;
      }
  
      function getCategory(name) {
          console.log("getCategories:");
          console.log(categories[name]);
          return categories[name];
      }
  
      function getJSON() {
      //JSON stuff, where categories gets its initial values.
      }
  </code></pre>
  
  <p>I call getCategory(name) in many places, and in some instances, it is called before <code>categories</code> has populated, e.g:</p>
  
  <pre><code> $scope.category = DataService.getCategory(name);
   //$scope.category is undefined
  </code></pre>
  
  <p>How can I build this Service so that getCategories waits until categories is defined before returning its value? Alternately, how can I write the Controller so that getCategories isn't defined until categories has a value? I have tried using a $scope.$watch function in the controller to watch DataService.categories, to no success- it never logs an updated value.</p>