Mike Mike - 1 month ago 7x
AngularJS Question

Store JSON file contents on load

Right now, I have a factory which loads a JSON file.

angular.module("app").factory("RolesFactory", ['$http', '$q', function($http, $q) {
var d = $q.defer();
$http.get('events.json').success(function(data) {
return d.promise;

And then I call this factory when I need the contents of events.json with this controller:

App.controller('rolesCtrl', ['$scope', 'RolesFactory', function($scope, RolesFactory) {
$scope.roles = roleData.roles;

All good, but whenever I need to use this data. Isn't it refetching the contents of events.json? Meaning: is Angular reloading the file over and over again? I was hoping to load the file once and call it by a global variable or something.

When my app loads initially, I want it to load and store the contens of events.json -- and then I'd like my app to be able to use this data whenever/wherever.

Is this possible?


As AngularJS is a stateless framework, you have only a few options here, all of which are some kind of client-side caching:

  1. Use localStorage to store your data. Once the data is fetched, you can just save it to localStorage using localStorage.setItem after Stringifying the JSON. You'll need to re-parse the JSON the next time you use it though, so if this is a giant JSON, this is not the best idea
  2. Use sessionStorage to store your data. This is exactly the same as #1, but you will lose data upon termination of session,i.e. closing your browser.
  3. Trust the JSON to be cached in your browser. This is most likely the case. Static assets are by default cached by most modern browsers. So, the second time your factory requests the JSON, the resource isn't actually fetched from the server. It is merely pulled from the browser's cache.

NOTE: The way to check this is to see what the HTTP status code for your resource is, in Chrome's Developer Tools Network tab. If the status says 304 that means it has been pulled from cache.

enter image description here