【问题标题】:How to use localstorage with AngularJS?如何在 AngularJS 中使用本地存储?
【发布时间】:2017-08-23 21:49:02
【问题描述】:

当我将新任务添加到我的任务管理器时,它会将其保存在 localStorage 中,但如果不更新就无法在页面上显示它。我需要使用 $watch 还是别的什么?

代码在这里:

$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 = "";
  }
};
<tr ng-repeat="task in retrievedTasks">
  <td>
    <button class="btn btn-danger" ng-click="deleteTask(task)">Delete</button>
    <!--  $index-->
  </td>
  <td>{{task.taskName}}</td>
  <td>
    <input type="checkbox" ng-model="statusCheck"> </td>
  <td style="{{setStyleToTd(statusCheck)}}">{{statusChecker(statusCheck)}}</td>
  <td>
    <button class="btn btn-primary" ng-click="editTask(task)">Edit</button>
  </td>
</tr>

【问题讨论】:

  • 我也尝试使用 $window.localstorage 但它没有用:(
  • 你真的需要两个作用域变量-$scope.retrivedTasks 和$scope.tasks 吗?如果没有,只需将 html 和 js 中的 $scope.retrievedTasks 替换为 $scope.tasks 即可。

标签: javascript angularjs local-storage


【解决方案1】:

您的视图正在使用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 = "";
    }
};

【讨论】:

  • 控制台中的一些角度错误,也许是因为我使用本地存储而不是角度替代?我见过一些 $localStorage 的东西
【解决方案2】:

希望对您有所帮助。

 $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`

【讨论】:

    猜你喜欢
    • 2013-08-17
    • 2015-12-05
    • 1970-01-01
    • 1970-01-01
    • 2015-01-07
    • 1970-01-01
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多