Skip to content

Instantly share code, notes, and snippets.

@davidpp
Created August 20, 2013 01:34
Show Gist options
  • Select an option

  • Save davidpp/6276159 to your computer and use it in GitHub Desktop.

Select an option

Save davidpp/6276159 to your computer and use it in GitHub Desktop.
/*global localStorage*/
/**
* The Cacher Module with the service CacheLocal
*/
angular.module('Cacher', []).
factory('CacheLocal', function($cacheFactory) {
var cache = $cacheFactory('someCache', {});
var PREFIX = 'Cacher::';
cache.get = function(key) {
console.log('get', key);
var lruEntry = localStorage.getItem(PREFIX + key);
if (!lruEntry) return; // Cache miss
lruEntry = JSON.parse(lruEntry);
console.log('hit', lruEntry);
return lruEntry.data; // Cache hit
};
cache.put = function(key, value) {
if (typeof value.then === 'function') {
value.then(function(value) {
localStorage.setItem(PREFIX + key, JSON.stringify(value));
});
} else {
localStorage.setItem(PREFIX + key, JSON.stringify(value));
}
};
cache.remove = function(key) {
localStorage.removeItem('Cacher::' + key);
};
cache.removeAll = function() {
localStorage.clear();
};
return cache;
});
var app = angular.module('Test', ['Cacher'])
.factory('AJAX', function($http, CacheLocal) {
return {
getWord: function(file) {
var promise = $http.get(file, {
cache: CacheLocal
}).then(function(d) {
return d.data;
});
return promise;
}
};
})
.controller('MainCtrl', function($scope, AJAX) {
$scope.obj = {
filename: 'test.txt',
result: ''
};
$scope.refresh = function() {
if (!this.obj.filename) return;
this.obj.result = AJAX.getWord(this.obj.filename);
};
$scope.refresh();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment