Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I store data in local storage using Angularjs?

Tags:

angularjs

People also ask

Can we store data in local storage?

LocalStorage is a key/value datastore that's available on a user's browser. Like cookies, LocalStorage can only store string data for its keys and values. The datastore is only accessible to JavaScript within that domain. Note: Each domain has access to its LocalStorage datastore.

How does local storage work in Angular?

Local storage is client-side storage for web applications. It stays there as long as it's not cleared—unlike session storage, which lasts for the current browser tab session. Local storage provides up to 5MB of storage, allocated separately for each domain.


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;
}]);

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.


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/


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