Created
August 26, 2014 18:43
-
-
Save jorgecasar/61fda6590dc2bb17e871 to your computer and use it in GitHub Desktop.
It's an Angular Factory with $fakeStorage fallback. LocalStorage is not working in Safari, then we create a session storage in a local variable. Take care about the data you save on it, remember that it's a local variable.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
angular.module('myApp.factories', []) | |
.factory('$fakeStorage', [ | |
function(){ | |
function FakeStorage() {}; | |
FakeStorage.prototype.setItem = function (key, value) { | |
this[key] = value; | |
}; | |
FakeStorage.prototype.getItem = function (key) { | |
return typeof this[key] == 'undefined' ? null : this[key]; | |
} | |
FakeStorage.prototype.removeItem = function (key) { | |
this[key] = undefined; | |
}; | |
FakeStorage.prototype.clear = function(){ | |
for (var key in this) { | |
if( this.hasOwnProperty(key) ) | |
{ | |
this.removeItem(key); | |
} | |
} | |
}; | |
FakeStorage.prototype.key = function(index){ | |
return Object.keys(this)[index]; | |
}; | |
return new FakeStorage(); | |
} | |
]) | |
.factory('$localstorage', [ | |
'$window', '$fakeStorage', | |
function($window, $fakeStorage) { | |
function isStorageSupported(storageName) | |
{ | |
var testKey = 'test', | |
storage = $window[storageName]; | |
try | |
{ | |
storage.setItem(testKey, '1'); | |
storage.removeItem(testKey); | |
return true; | |
} | |
catch (error) | |
{ | |
return false; | |
} | |
} | |
var storage = isStorageSupported('localStorage') ? $window.localStorage : $fakeStorage; | |
return { | |
set: function(key, value) { | |
storage.setItem(key, value); | |
}, | |
get: function(key, defaultValue) { | |
return storage.getItem(key) || defaultValue; | |
}, | |
setObject: function(key, value) { | |
storage.setItem(key, JSON.stringify(value)); | |
}, | |
getObject: function(key) { | |
return JSON.parse(storage.getItem(key) || '{}'); | |
}, | |
remove: function(key){ | |
storage.removeItem(key); | |
}, | |
clear: function() { | |
storage.clear(); | |
}, | |
key: function(index){ | |
storage.key(index); | |
} | |
} | |
} | |
]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this.