title: How would I create a factory that only queries the database once, but can be used by many controllers?
body: <p>I have a 'messages' factory that will query my database for a list of messages.</p>
  
  <p>I'm using the list of messages in two different places. Once to add a message count indicator, and then once to show a list of messages. Since I'm injecting the service into two different controllers, it seems like it's creating two instances of my factory, and hitting the database twice for the list.</p>
  
  <p>How would I set things up to only ask for the list once, and use the list for both display and count purposes in both controllers?</p>
  
  <p>My factory looks like this:</p>
  
  <pre><code>myApp.factory('messagesService', [
      '$rootScope',
      function($rootScope) {
          var messages = [];
  
          function query() {
              // Would actually hit the database asyncronously
              messages = ['one', 'two', 'three', 'four'];
              console.log('query');
              $rootScope.$emit('messages.update');
          }
  
          function all() {
              return messages;
          }
  
          return {
              query: query,
              all: all
          }
      }
  ]);
  </code></pre>
  
  <p>My controllers are using blocks like this to watch for changes:</p>
  
  <pre><code>$rootScope.$on('messages.update', function() {
      $scope.messagesCount = messagesService.all().length;
  });
  </code></pre>
  
  <p>But it means i need a <code>messagesService.query();</code> in each controller for things to be reliable.</p>
  
  <p>So here are a few jsFiddle examples of it as I have things now:</p>
  
  <ol>
  <li>Doesn't work (only updates the header): <a href="http://jsfiddle.net/TSLfc/1/" rel="nofollow">http://jsfiddle.net/TSLfc/1/</a></li>
  <li>Works but would break if I didn't load the dashboard controller:
  <a href="http://jsfiddle.net/TSLfc/2/" rel="nofollow">http://jsfiddle.net/TSLfc/2/</a></li>
  <li>Works every time, but queries the server twice:
  <a href="http://jsfiddle.net/TSLfc/3/" rel="nofollow">http://jsfiddle.net/TSLfc/3/</a></li>
  </ol>
  
  <p>Is there a better way to organize my code? Should I build out the messages factory into it's own full module?</p>