- Place your shared resource into a service (this is almost always how you share data between controllers).
- Cache the results within the service so the expensive query need only be performed once.
Since both $http and $resource support caching out of the box, you don't need to write your own caching. To tweak the default caching behavior, check out $cacheFactory.
Here's an example from an application I'm working on:
var app = angular.module('app', ['ngResource']);
app
.factory('Worklogs', function($resource) {
return $resource('/tempo/worklogs', {}, {
'query': {method:'GET', isArray:true, cache: true}
});
})
.controller('FirstCtrl', function($scope, Worklogs, $log, $filter){
$scope.search = SearchParameters;
$scope.worklogs = Worklogs.query({dateFrom: $scope.search.dateFrom, dateTo: $scope.search.dateTo});
})
.controller('SecondCtrl', function($scope, Worklogs, $log, $filter){
$scope.search = SearchParameters;
$scope.worklogs = Worklogs.query({dateFrom: $scope.search.dateFrom, dateTo: $scope.search.dateTo});
})
The first time a controller loads and each time new parameters are passed into query(), the Worklogs service makes an HTTP request. Whenever a controller is changed and a previous query is repeated, Worklogs are loaded from the cache (and no HTTP request is made).
I'm using AngularJS 1.1.5 since the 1.0.x branch is missing loads of cool stuff...probably including this.