I'm new to angular and I need to cache data to increase the performance. For this I'm using $cacheFactory by Angular.
When I try,
myApp.factory('myCache', function($cacheFactory) {
return $cacheFactory('myData');
});
With
myApp.controller('MyMain', ['$scope', '$http', 'myCache',
function ($scope, $http, myCache) {
var cache = myCache.get('myData');
if (cache) {
$scope.variable = cache;
}
else {
$http.get('http://www.example.com/path/to/api/endpoint')
.success(function(data) {
$scope.variable = data;
myCache.put('myData', data);
}
);
}
}
This works fine, but it only caches one set of data, as I want to cache multiple set of data I uses
myApp.factory('myCache', function($cacheFactory) {
return {
get : function(cacheKey){
return $cacheFactory(cachekey);
}
}
});
So if I go to another page I can cache another set of data like this,
myApp.controller('MyMain', ['$scope', '$http', 'myCache',
function ($scope, $http, myCache) {
var cache = myCache.get('myData2');
if (cache) {
$scope.variable = cache;
}
else {
$http.get('http://www.example.com/path/to/api/endpoint')
.success(function(data) {
$scope.variable = data;
myCache.put('myData2', data);
}
);
}
}
etc.
However in the latter way although it doesn't give any error no data is returned and no ajax call is made to cache the data.
How can I fix this? And cache multiple sets of data using $cacheFactory?