I have a multi-tab application with two separate controllers.
When one tab is entered, I need to click on the API. The answer is not updated after the first press, so there is no need to hit it again on subsequent visits to this tab.
My question is what is the proper way to cache an API response and set it to a scope variable.
I currently have a help function similar to this
var setAndCache = function(scope, cacheFactory, cacheKey, cacheValue) { scope[cacheKey] = cacheValue; cacheFactory.put(cacheKey, cacheValue); };
Factory cache setting so
factory('TabData', function($cacheFactory) { return $cacheFactory('tabData'); }).
which is entered 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')); }
It works great, but it feels ... dirty. Is there a better way to achieve the same?
source share