我正在创建一个示例待办事项应用程序,我可以在其中添加/删除任务,但是当我刷新页面时,数据会丢失。因此,我决定使用 localStorage
来保存任务列表并在页面刷新时检索它。
我可以做同样的事情,但我只能以数组列表的形式检索数据。我如何才能一一列出存储在 localStorage
中的任务并以与页面加载之前完全相同的方式显示它?
HTML 代码
<body ng-app="todoApp">
<div ng-controller="addTaskController" data-ng-init="init()">
<div class="container">
<h3>ToDo Application</h3>
<div class="form-group col-md-6">
<form ng-submit="addTask()" class="form-inline">
<input type="text" placeholder="Enter Your Task" ng-model="newTask" class="form-control">
<button type="submit" class="btn btn-primary">Add Task</button>
<div class="taskList">
<ol>
<li ng-repeat="task in tasks track by $index">{{task}} <i style="color:red;margin-left:10px;cursor:pointer;" class="fa fa-times" aria-hidden="true" ng-click="deleteTask()" data-toggle="tooltip" title="Delete Task"></i></li>
<p ng-show="tasks.length==0">No Tasks Available </p>
</ol>
</div>
</form>
</div>
</body>
JS 代码
var todoApp = angular.module('todoApp',[]);
todoApp.controller('addTaskController',function($scope){
$scope.tasks = [];
$scope.addTask = function() { // Function to add a task to list
if($scope.newTask == null) {
alert("Please enter a task");
} else {
$scope.tasks.push($scope.newTask);
localStorage.setItem("storedTasks", JSON.stringify($scope.tasks));
$scope.newTask = null;
}; // add() ends
}
$scope.deleteTask = function() {
$scope.tasks.splice(this.$index, 1);
localStorage.removeItem("storedTasks");
};
$scope.init = function() {
$scope.retrievedData = localStorage.getItem("storedTasks");
if($scope.retrievedData != null) {
$scope.tasks.push($scope.retrievedData);
} else {
tasks.length==0;
}
}
});
页面重新加载之前
页面重新加载后
我该如何解决这个问题
最佳答案
RetrievedData
是一个数组,您必须迭代并将每个项目推送到 tasks
对象。您现在正在做的是将整个数组转储到单个任务中。
if($scope.retrievedData != null){
$scope.retrievedData.forEach(function(item){
$scope.tasks.push(item);
})
}
关于javascript - 从本地存储中一一检索数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36839531/