AngularJS Cache HTTP result

by Chad Drummond

JavaScript

myApp.service('CountryData', function($q, $http) {
    var deferred;
    var CountryData = {
      get: function() {
        return deferred.promise;
      },
      refresh: function() {
        deferred = $q.defer();

        $http.get(URL, {
          params: params
        }).then(function(results) {
          deferred.resolve(results.data.geonames);
        });

        return this;
      }
    };

    CountryData.refresh();

    return CountryData;
  });

  // Usage example
  CountryData.refresh().get().then(function(results) {
    $scope.results = results;
  });