I'm loading JSON in my controller, changing routes the JSON gets reloaded. I would like to cache it.
var sampleApp = angular.module('sampleApp', [
'ngRoute',
'sampleAppControllers',
]);
var sampleControllers = angular.module('sampleControllers', []);
sampleControllers.controller('PostsCtrl', ['$scope', '$http',
function($scope, $http) {
// Should be loaded only on app load
$http.get('http://example.org/source.json').success(function(data) {
$scope.posts = data;
});
$scope.orderProp = 'id';
}]);
I tried using .constant, but couldn't get it work:
sampleApp.constant('myCache', ['$http',
function($http) {
$http.get('http://example.org/source.json').success(function(data) {
return data;
});
}]);
sampleControllers.controller('PostsCtrl', ['$scope', 'myCache',
function($scope, myCache) {
$scope.posts = myCache;
$scope.orderProp = 'id';
}]);
I'm looking for a way to load JSON on app start, and use it in controllers.