Skip to content

Instantly share code, notes, and snippets.

@Alexintosh
Created March 18, 2015 11:59
Show Gist options
  • Save Alexintosh/8e8dd716860c8fdcd08a to your computer and use it in GitHub Desktop.
Save Alexintosh/8e8dd716860c8fdcd08a to your computer and use it in GitHub Desktop.
Angular factory for local storage
.factory('$localstorage', ['$window', function($window) {
return {
set: function(key, value) {
$window.localStorage[key] = value;
},
get: function(key, defaultValue) {
return $window.localStorage[key] || false;
},
setObject: function(key, value) {
$window.localStorage[key] = JSON.stringify(value);
},
getObject: function(key) {
if($window.localStorage[key] != undefined)
return JSON.parse($window.localStorage[key] || false );
return false;
},
remove: function(key){
$window.localStorage.removeItem(key);
},
clear: function(){
$window.localStorage.clear();
}
}
}])
@temitope
Copy link

update the get function's return statement if you will use a defaultValue.
get: function(key, defaultValue) {
return $window.localStorage[key] || defaultValue || false;
}
thanks for this.
i like the clear function added

@Alexintosh
Copy link
Author

Sorry it took so long @temitope I've just seen the comment!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment