AngularJs: store and retrieve data in local storage

Problem

I am very new to Angular. Earlier I was using Javascript, but now I am learning AngularJs. Version currently using is 1.3.2.

Problem is I am trying to use local storage.

In Javascript, we use something similar to this:

localStorage.pic = data.pic;
localStorage.id = data.uid;
localStorage.name = data.name;

Is there anything similar to this in AngularJs?

Thanks for your advise.

Problem courtesy of: Calculating Machine

Solution

It's the same way using ngStorage,

Add ngStorage reference and inject it as a depdency to your angular app,

<script type="text/javascript" src='https://rawgithub.com/gsklee/ngStorage/master/ngStorage.js'></script>

angular.module('gameApp', ['ngStorage'])

Then you can store and retrieve like this,

 $localStorage.pic= $scope.pic;

DEMO

angular.module('gameApp', ['ngStorage', 'ui.bootstrap'])
  .controller('MainCtrl', ['$scope', '$localStorage', function ($scope, $localStorage) {

    // Set a total score variable equal to zero
    $scope.total = 0;

    // NOTE: use d3.js for data visualization in widget

    var gameData = [
      {
        "level": "Level One",
        "points": 30,
        "max": 100,
        "completed": false
      },
      {
        "level": "Level Two",
        "points": 50,
        "max": 100,
        "completed": false   
      }
    ];

    // tie the game JSON to the view
    $scope.gameData = gameData; 
    
    // tie the view to ngModule which saves the JSON to localStorage
    $localStorage.gameData = gameData;

    // loop through the gameData and sum all the values where the key = 'points'



    console.log("Your current score is: " + $scope.total)
    $localStorage.total = $scope.total;

    $scope.addToLevel = function(level, num){
       $scope.levelPoints = gameData[level].points += num;
       console.log("You have " + $scope.levelPoints + " points in Level");
    }


    // create a function that loops the json to check if the points >= max 
      // and if so
        // then change completed to true
   
    $scope.calcTotal = function(){
        for (var i in $scope.gameData){
          var level = $scope.gameData[i];
          $scope.total += level.points;
      }
      $localStorage.total = $scope.total;
    };


    $scope.calcTotal();



  }])
<!DOCTYPE html>
<html ng-app='gameApp'>

<head>
  <meta charset="utf-8" />
  <title>Angular Local storage</title>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">
  <script type="text/javascript" src='https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js'></script>
  <script type="text/javascript" src='https://rawgithub.com/gsklee/ngStorage/master/ngStorage.js'></script>
  <script src="https://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.12.1.js"></script>

  <script type="text/javascript" src='script.js'></script>


</head>

<body ng-controller='MainCtrl'>
  <!-- Fixed navbar -->
  <nav class="navbar navbar-default navbar-fixed-top">
    <div class="container">
      <div class="navbar-header">
        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand" href="#">Angular JS Local Storage</a>
      </div>
    </div>
   
  </nav>


  <div class='container'>
    <div class='row' style='margin-top:100px'>
      <button class='btn btn-primary' ng-click="addToLevel(0, 20); calcTotal();">+20 Points Lvl 1</button>
      <br>

      <table class='table table-hover'>
        <thead>
          <tr>
            <td>Level</td>
            <td>Points</td>
          </tr>
        </thead>
        <tbody>
          <tr ng-repeat='data in gameData'>
            <td>{{ data.level }}</td>
            <td>{{ data.points }}</td>
          </tr>
          <tr>
            <td>Total Points</td>
            <td>{{total}}</td>
          </tr>
        </tbody>
      </table>


    </div>
  </div>


</body>

</html>

Solution courtesy of: Sajeetharan

Discussion

You can create a common factory service that will save and return the saved local storage data based on the key.

app.factory('storageService', ['$rootScope', function($rootScope) {

    return {
        get: function(key) {
            return localStorage.getItem(key);
        },
        set: function(key, data) {
            localStorage.setItem(key, data);
        }
    };
}]);

In controller :

Inject the storageService dependency in the controller to set and get the data from the local storage.

app.controller('myCtrl',['storageService',function(storageService) {

  // Set local storage data to storageService
  storageService.set('key', 'value');

  // Get saved local storage data from storageService
  var data = storageService.get('key');

});
Discussion courtesy of: Rohit Jindal

JavaScript will remain same whether you use angular or other frameworks.You are doing wrong , localStorage has setItem() and getItem() methods . Try this

localStorage.setItem('pic',data.pic);
localStorage.setItem('id',data.id);
localStorage.setItem('name',data.name);

And retrieval like this

localStorage.getItem('pic');
localStorage.getItem('id');
localStorage.getItem('name');
Discussion courtesy of: Ghazanfar Khan

This recipe can be found in it's original form on Stack Over Flow.