How do I store data in local storage using Angularjs?
If you use $window.localStorage.setItem(key,value)
to store,$window.localStorage.getItem(key)
to retrieve and $window.localStorage.removeItem(key)
to remove, then you can access the values in any page.
You have to pass the $window
service to the controller. Though in JavaScript, window
object is available globally.
By using $window.localStorage.xxXX()
the user has control over the localStorage
value. The size of the data depends upon the browser. If you only use $localStorage
then value remains as long as you use window.location.href to navigate to other page and if you use <a href="location"></a>
to navigate to other page then your $localStorage
value is lost in the next page.
this is a bit of my code that stores and retrieves to local storage. i use broadcast events to save and restore the values in the model.
app.factory('userService', ['$rootScope', function ($rootScope) {
var service = {
model: {
name: '',
email: ''
},
SaveState: function () {
sessionStorage.userService = angular.toJson(service.model);
},
RestoreState: function () {
service.model = angular.fromJson(sessionStorage.userService);
}
}
$rootScope.$on("savestate", service.SaveState);
$rootScope.$on("restorestate", service.RestoreState);
return service;
}]);
Use ngStorage
For All Your AngularJS Local Storage Needs. Please note that this is NOT a native part of the Angular JS framework.
ngStorage
contains two services, $localStorage
and $sessionStorage
angular.module('app', [
'ngStorage'
]).controller('Ctrl', function(
$scope,
$localStorage,
$sessionStorage
){});
Check the Demo
For local storage there is a module for that look at below url:
https://github.com/grevory/angular-local-storage
and other link for HTML5 local storage and angularJs
http://www.amitavroy.com/justread/content/articles/html5-local-storage-with-angular-js/