I have a multi tabbed application, with two separate controllers.
When either tab is entered, I need to hit an API. The response doesn't update after the initial hit, so there is no need to hit it again on subsequent visits to that tab.
My question is what is the correct way to cache the API response, and set it to a scope variable.
Currently, I have a helped function setup like this
var setAndCache = function(scope, cacheFactory, cacheKey, cacheValue) {
scope[cacheKey] = cacheValue;
cacheFactory.put(cacheKey, cacheValue);
};
A cache factory setup like so
factory('TabData', function($cacheFactory) {
return $cacheFactory('tabData');
}).
that gets injected into each controller
controller('TabOne', function($scope, $http, TabData) {
var setupCache = function(response) {
setAndCache($scope, TabData, 'tabOneData', response);
};
if (!TabData.get('tabOneData')) {
$http.get('/path/to/api')
.success(function(response) {
setupCache(response);
});
}
else {
setupCache(TabData.get('tabOneData'));
}
This works fine, but feels...dirty. Is there a better way to achieve the same thing?