从本地存储刷新页面后数据丢失

时间:2016-10-17 10:27:45

标签: javascript angularjs

我将用户信息存储到本地存储中,但每次重新加载页面数据都会丢失。没有得到确切的解决方案。这是我的js代码。我正在以这种格式从html获得用户对象的价值

    {"fname":"A","lname":"B","age":"12","email":"a@b.com","class":"6","password":"1234"}

这是我的js代码

    var app = angular.module("myApp",["ngStorage"]);

   app.controller("myCtrl", function($scope,$localStorage,
     $sessionStorage) {
     var usersinfo= [];
     $scope.submit = function() {
       usersinfo.push($scope.user);
       localStorage.setItem("usersinfo", JSON.stringify(usersinfo));

      console.log(usersinfo);    
     };   

});

2 个答案:

答案 0 :(得分:0)

您正在导入$ localStorage并使用localStorage。

有关读/写语法,请参阅documentation

答案 1 :(得分:0)

以下示例在HTML文件中单独执行时工作正常(不要指望它在StackOverflow执行环境中加载localStorage)

var user = {
  "fname": "A",
  "lname": "B",
  "age": "12",
  "email": "a@b.com",
  "class": "6",
  "password": "1234"
};
var app = angular.module("app", []);

app.controller("MyController", function($scope) {
  console.log('Loaded');
  $scope.usersinfo = [];
  $scope.show = function() {
    $scope.usersinfo = JSON.parse(localStorage.getItem('usersinfo'));
    console.log($scope.usersinfo)
  };
  $scope.submit = function() {
    $scope.usersinfo.push(user);
    localStorage.setItem("usersinfo", JSON.stringify($scope.usersinfo));

    console.log($scope.usersinfo);
  };

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="MyController">
    <p>Hi</p>
    <button type="button" ng-click="submit()">Submit</button>
    <button type="button" ng-click="show()">Show</button>
    <p>{{usersinfo}}</p>
  </div>
</div>