从本地存储中检索数据时出错

时间:2017-06-10 09:55:32

标签: angularjs ionic-framework

当我重新打开我的应用程序时,我无法检索数据。我该怎么做才能永久保存数据 我试过这段代码:

<body ng-app="starter" ng-controller="Appctrl">
  <form data-ng-submit="addTodo()" class="todo-form">
    <input type="text" data-ng-model="todoText" placeholder="Enter new ToDo 
    item" />
    <br />
    <input type="submit" value="Add Task" />
  </form>

  <ul class="unstyled">
    <li data-ng-repeat="item in todo track by $index">
      <input type="text">
      <span>{{ item.text }}</span>
    </li>
  </ul>

</body>

并在app.js中:

.controller("Appctrl", function($scope) {
  $scope.addTodo = function() {
    $scope.text = $scope.todoText;
    $scope.todos = [];
    $scope.todo.push(text);
    $scope.todoText = ''; //clear the input after adding
    localStorage.setItem('todo', JSON.stringify($scope.todo));
    $scope.saved = localStorage.getItem('todo');
    localStorage.setItem('todo', JSON.stringify($scope.saved));
  };
});

4 个答案:

答案 0 :(得分:1)

从本地存储检索数据时检查是否存在,然后{{1}}从本地存储获取

答案 1 :(得分:0)

在你的情况下:

//you will need to parse the string to store it as an object
$scope.saved = JSON.parse(localStorage.getItem('todo'));

您可以使用以下工厂:

yourApp.factory('$localStorage', ['$window', function($window) {
        return {
            store: function(key, value) {
                $window.localStorage[key] = value;
            },
            get: function(key, defaultValue) {
                return $window.localStorage[key] || defaultValue;
            },
            storeObject: function(key, value) {
                $window.localStorage[key] = JSON.stringify(value);
            },
            getObject: function(key,defaultValue) {
                return JSON.parse($window.localStorage[key] || defaultValue);
            }
        }
    }]);

要使用工厂,您应将其注入控制器并按以下方式使用:

//to store
$localStorage.storeObject("sometoken", data);

//to retrieve
$localStorage.getObject("sometoken", "");

答案 2 :(得分:0)

我解决了我的问题:

.controller( “Appctrl”,功能($范围){

$scope.saved = localStorage.getItem('id');
$scope.id = JSON.parse($scope.saved);
localStorage.setItem('id', JSON.stringify($scope.id));


$scope.addTodo = function() {
//$scope.text=$scope.todoText;
$scope.id = [];
    $scope.id.push({text:$scope.idText});

    $scope.idText = ''; //clear the input after adding
    localStorage.setItem('id', JSON.stringify($scope.id));

};

});

答案 3 :(得分:0)

检查控制器中的代码。 您正在执行:$scope.todo.push(text);而不是$scope.todos.push(text); itseems