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?

mauris
  • 42,982
  • 15
  • 99
  • 131

10 Answers10

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;
}]);
Anton
  • 7,709
  • 5
  • 31
  • 33
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.

Muhammad bin Yusrat
  • 1,433
  • 1
  • 14
  • 19
Sunil Gouda
  • 1,111
  • 1
  • 7
  • 2
  • 13
    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. – Brett Donald May 12 '16 at 01:16
  • 5
    This is the best answer. No external dependencies needed. – Kasper Ziemianek Aug 09 '16 at 09:10
  • 2
    Agreed, this is the simplest solution for key/value pair management – jolySoft Jan 26 '17 at 11:30
  • What is key in the line: $window.localStorage.setItem(key,value). Where is it declared and set ? –  Dec 13 '17 at 09:11
  • 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. – user441521 Mar 23 '18 at 14:15
  • Is there some example for this? When I try to use it, I get the following error: https://code.angularjs.org/1.6.9/docs/error/$injector/modulerr?p0=root&p1=%5B$injector:nomod%5D%20http:%2F%2Ferrors.angularjs.org%2F1.6.9%2F$injector%2Fnomod%3Fp0%3Droot%0AK%2F%3C@https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.6.9%2Fangular.min.js:7:76%0ACe%2F%3C%2F%3C%2F%3C@https:%2F – Sumit Apr 16 '18 at 17:41
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/

beat
  • 1,857
  • 1
  • 22
  • 36
JQuery Guru
  • 6,943
  • 1
  • 33
  • 40
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

Al Fahad
  • 2,378
  • 5
  • 28
  • 37
Jethik
  • 1,860
  • 1
  • 22
  • 26
4

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

angular-local-storage:

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

The Bndr
  • 13,204
  • 16
  • 68
  • 107
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!

Al Fahad
  • 2,378
  • 5
  • 28
  • 37
Yaacov
  • 185
  • 4
  • Would the down voters care to explain their votes, please? – DerMike Oct 13 '16 at 10:16
  • 1
    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 ! – JR Utily Feb 01 '17 at 10:02
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
Evan Bechtol
  • 2,855
  • 2
  • 18
  • 36
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

Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79
sam ruben
  • 365
  • 2
  • 6
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.

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>
Aniket Jha
  • 1,751
  • 11
  • 13