Check out a working demo: JSFiddle
First of all, using a factory may be more appropriate for your case.
You need to play deferred / promise manually. If the requested id is already loaded, immediately resolve the pending object. Otherwise, send an HTTP request (in the demo, I just used a public API that provides fake data ) and retrieved project information.
app.factory('ProjectFactory', ['$http', '$q', function ($http, $q) { var myProject; return { project: function (id) { var deferred = $q.defer(); // If the requested id is fetched already, just resolve if (!id || (myProject && myProject.id === id)) { console.log('get from cache'); deferred.resolve(myProject); } else { console.log('sending request...'); $http.get('http://jsonplaceholder.typicode.com/posts/' + id).success(function (response) { myProject = response; deferred.resolve(myProject); }).error(function (response) { deferred.reject(response); }); } return deferred.promise; } }; }]);
To use this factory:
app.controller('JoyCtrl', ['$scope', '$timeout', 'ProjectFactory', function ($scope, $timeout, ProjectFactory) { ProjectFactory.project(1).then(function (project) { $scope.project = project; ProjectFactory.project(1).then(function (project) { }); }, function (reason) { console.log('Failed: ' + reason); }); }]);
For reference: $http , $q
source share