title: AngularJS/Ionic Service Factory Cache
body: <p>I'm trying to "cacheify" my angular service factory. I want it to use the cache to hit the URL only the first time the page is loaded. Then when I browse to my detail page (findById) I want to use the cache. Does this make sense?</p>
  
  <p>Below is what I have right now but I can't figure out a solid way to handle this async. My controller is calling into the service.</p>
  
  <pre><code>angular.module('myapp.services', [])
  
  .factory('myservice', function ($http, $q, $cacheFactory) {
  
      var url = '//myurl.com/getawesomeJSON';
  
      return {
  
          findAll: function () {
  
              var $httpDefaultCache = $cacheFactory.get('$http');
  
              var data = $httpDefaultCache.get(url);
              if (data == null) {
                  data = $http.get(url, { cache: true });
              }
  
              var deferred = $q.defer();
              deferred.resolve(data);
              return deferred.promise;
          },
  
          findById: function (id) {
  
              var data = angular.fromJson($cacheFactory.get('$http').get(url)[1]);
  
              for (var i = 0; i &lt; data.length; i++) {
  
                  if (data[i].Id === parseInt(id)) {
  
                      var deferred = $q.defer();
                      deferred.resolve(data[i]);
                      return deferred.promise;
                  }
              }
          }
      }
  });
  </code></pre>