AngularJs:在本地存储中存储和检索数据

时间:2017-01-15 16:51:39

标签: angularjs

我对Angular很新。早些时候我使用的是Javascript,但现在我正在学习AngularJs。目前使用的版本是1.3.2。

问题是我正在尝试使用本地存储。

在Javascript中,我们使用类似的东西:

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

AngularJs中有类似的内容吗?

感谢您的建议。

3 个答案:

答案 0 :(得分:6)

使用ngStorage也是一样,

添加ngStorage引用并将其作为一个depdency注入您的角度应用程序,

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

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

然后你可以像这样存储和检索

 $localStorage.pic= $scope.pic;

<强>样本

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>

答案 1 :(得分:4)

您可以创建一个公共工厂服务,该服务将根据密钥保存并返回保存的本地存储数据。

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

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

在控制器中:

在控制器中注入storageService依赖项,以设置并从本地存储中获取数据。

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');

});

答案 2 :(得分:1)

无论你使用angular还是其他框架,JavaScript都将保持不变。你做错了,localStorage有setItem()和getItem()方法。 试试这个

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

像这样检索

localStorage.getItem('pic');
localStorage.getItem('id');
localStorage.getItem('name');