How do I store data in local storage using Angularjs?
Asked Answered
P

10

179

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?

Penitentiary answered 15/8, 2013 at 5:59 Comment(0)
K
124

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;
}]);
Kristykristyn answered 15/8, 2013 at 13:53 Comment(10)
chovy, here is the complete angular example #12941474Kristykristyn
For the record sessionStoragelocalStorageBaillargeon
agreed, the terms do not match, but the spec suggests to me it is stored on the client, which i inferred is what is meant in the original question. w3schools.com/html/html5_webstorage.aspKristykristyn
you could use $window.sessionStorage so you can inject it in your testsVirginia
@GuillaumeMassé what is your recommendation as a w3schools alternative?Kristykristyn
@Kristykristyn mozilla has solid documentation: developer.mozilla.org/en-US/docs/Web/HTML developer.mozilla.org/en-US/docs/Web/CSS/CSS3 developer.mozilla.org/en-US/docs/Web/JavaScriptVirginia
what is the lifetime of localStorage ?Cab
∞ normally, but may be reset by browsers/extensionsProudman
@GuillaumeMassé I agree, it should be used $window.sessionStorage (localStorage), to allow mocking in testing.Sumba
I don't think that giving an answer for session storage is anyway correct, if one is asking for localstorage.Acidimeter
C
111

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.

Coracorabel answered 5/5, 2016 at 11:52 Comment(6)
This solution suited me best. Why use a plug-in or a module when you can just as easily go straight to the DOM? Because I wanted to store objects rather than simple strings, I just used angular.toJson() in combination with setItem() and angular.fromJson() in combination with getItem(). Easy. Love it.Degenerate
This is the best answer. No external dependencies needed.Opportune
Agreed, this is the simplest solution for key/value pair managementGalven
What is key in the line: $window.localStorage.setItem(key,value). Where is it declared and set ?Adamo
The key is whatever you want it to be that uniquely ID's the value. So YOU define the key when you store something and that's the same thing you use to retrieve it.Gravel
Is there some example for this? When I try to use it, I get the following error: code.angularjs.org/1.6.9/docs/error/$injector/…Tuantuareg
R
56

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/

Ringleader answered 15/8, 2013 at 6:6 Comment(1)
Link-only answers are discouraged on StackOverflow as external links tend to die.Aboutship
H
50

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

Hipolitohipp answered 4/3, 2015 at 11:33 Comment(2)
worth mentionning that is not part of angular, and should be imported as additional fileShifty
link to npm module?Rizo
B
4

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

angular-local-storage:

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

Baudelaire answered 17/4, 2015 at 14:7 Comment(0)
D
2

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!

Daniel answered 28/3, 2016 at 18:8 Comment(2)
Would the down voters care to explain their votes, please?Glossotomy
I use angular-stored-object in my project now, and it is really easy to use. More over, Yaacov is really quick in answering question. So I do recommend it too !Aggrieve
H
2

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
Huckaby answered 12/5, 2016 at 4:14 Comment(0)
F
2

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

Fuhrman answered 9/5, 2019 at 10:35 Comment(0)
N
1

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.

Nelidanelie answered 26/8, 2015 at 16:5 Comment(0)
L
1

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>
Lifelike answered 3/2, 2018 at 6:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.