How do I store data in local storage using Angularjs?

Angularjs

Angularjs Problem Overview


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?

Angularjs Solutions


Solution 1 - Angularjs

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 - 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.

Solution 3 - Angularjs

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 - Angularjs

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 - Angularjs

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

angular-local-storage:

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

Solution 6 - Angularjs

I authored (yet another) angular html5 storage service. I wanted to keep the automatic updates made possible by ngStorage, but make digest cycles more predictable/intuitive (at least for me), add events to handle when state reloads are required, and also add sharing session storage between tabs. I modelled the API after $resource and called it angular-stored-object. It can be used as follows:

  angular
    .module('auth', ['yaacovCR.storedObject']);

  angular
    .module('auth')
    .factory('session', session);

  function session(ycr$StoredObject) {
    return new ycr$StoredObject('session');
  }

API is here.

Repo is here.

Hope it helps somebody!

Solution 7 - Angularjs

You can use localStorage for the purpose.

Steps:

  1. add ngStorage.min.js in your file
  2. add ngStorage dependency in your module
  3. add $localStorage module in your controller
  4. use $localStorage.key = value

Solution 8 - Angularjs

Follow the steps to store data in Angular - local storage:

  1. Add 'ngStorage.js' in your folder.

  2. Inject 'ngStorage' in your angular.module

       eg: angular.module("app", [ 'ngStorage']);
    
  3. Add $localStorage in your app.controller function

4.You can use $localStorage inside your controller

Eg: $localstorage.login= true;

The above will store the localstorage in your browser application

Solution 9 - Angularjs

Depending on your needs, like if you want to allow the data to eventually expire or set limitations on how many records to store, you could also look at https://github.com/jmdobry/angular-cache which allows you to define if the cache sits in memory, localStorage, or sessionStorage.

Solution 10 - Angularjs

One should use a third party script for this called called ngStorage here is a example how to use.It updates localstorage with change in scope/view.

    <!DOCTYPE html>
<html>

<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <!-- CDN Link -->
    <!--https://cdnjs.cloudflare.com/ajax/libs/ngStorage/0.3.6/ngStorage.min.js-->
    <script src="angular.min.js"></script>
    <script src="ngStorage.min.js"></script>
    <script>
        var app = angular.module('app', ['ngStorage']);
        app.factory("myfactory", function() {
            return {
                data: ["ram", "shyam"]
            };
        })
        app.controller('Ctrl', function($scope, $localStorage, $sessionStorage, myfactory) {
            
            $scope.abcd = $localStorage; //Pass $localStorage (or $sessionStorage) by reference to a hook under $scope
            // Delete from Local Storage
            //delete $scope.abcd.counter;
            // delete $localStorage.counter;
            // $localStorage.$reset(); // clear the localstorage
            /* $localStorage.$reset({
                 counter: 42   // reset with default value
             });*/
            // $scope.abcd.mydata=myfactory.data;
        });
    </script>
</head>

<body ng-app="app" ng-controller="Ctrl">

    <button ng-click="abcd.counter = abcd.counter + 1">{{abcd.counter}}</button>
</body>

</html>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2601750View Question on Stackoverflow
Solution 1 - AngularjsAntonView Answer on Stackoverflow
Solution 2 - AngularjsSunil GoudaView Answer on Stackoverflow
Solution 3 - AngularjsJQuery GuruView Answer on Stackoverflow
Solution 4 - AngularjsJethikView Answer on Stackoverflow
Solution 5 - AngularjsThe BndrView Answer on Stackoverflow
Solution 6 - AngularjsYaacovView Answer on Stackoverflow
Solution 7 - AngularjsSukhminder ParmarView Answer on Stackoverflow
Solution 8 - Angularjssam rubenView Answer on Stackoverflow
Solution 9 - AngularjsAaron MorrisonView Answer on Stackoverflow
Solution 10 - AngularjsAniket JhaView Answer on Stackoverflow