How do I store data in local storage using Angularjs?

Currently I am using a service to perform an action, namely retrieve data from the server and then store the data on the server itself.

Instead of this, I want to put the data into local storage instead of storing it on the server. How do I do this?


Solution 1:

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

Solution 2:

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.

Solution 3:

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/

Solution 4:

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

Solution 5:

There is one more alternative module which has more activity than ngStorage

angular-local-storage:

https://github.com/grevory/angular-local-storage