如何在AngularJS中使用localstorage?

时间:2017-08-23 13:25:49

标签: javascript angularjs local-storage

当我向任务管理器添加新任务时,它将其保存在localStorage中,但无法在不更新的情况下在页面上显示。我是否需要使用$ watch或其他东西?

代码在这里:



<article #articleId id="bodyArticle" [class.hidden]="isClicked"></article>
&#13;
$scope.retrievedTasks = JSON.parse(localStorage.getItem('tasks'));
$scope.addTask = function() {
  console.log($scope.retrievedTasks)
  console.log($scope.tasks)
  if ($scope.newTaskName) {
    $scope.tasks.push({
      taskName: $scope.newTaskName,
      status: false
    });
    localStorage.setItem('tasks', JSON.stringify($scope.tasks));
    $scope.newTaskName = "";
  }
};
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

当您的控制器更新retrievedTasks时,您的观点正在使用$scope.tasks,因此如果您想继续使用retrievedTasks,请确保将其推送到该列表

$scope.addTask = function () {
    if ($scope.newTaskName) {
        $scope.retrievedTasks.push({
            taskName: $scope.newTaskName
            , status: false
        });
        localStorage.setItem('tasks', JSON.stringify($scope.retrievedTasks));
        $scope.newTaskName = "";
    }
};

答案 1 :(得分:0)

希望它会对你有所帮助。

 $scope.retrievedTasks = JSON.parse(localStorage.getItem('tasks'));
 $scope.addTask = function() 
 {
  console.log($scope.retrievedTasks)
  console.log($scope.tasks)
  if ($scope.newTaskName) {
    $scope.tasks = {
        taskName: $scope.newTaskName,
        status: false
    };
    localStorage.setItem('tasks', JSON.stringify($scope.tasks));
    $scope.newTaskName = "";
  }
 };`enter code here`