javascript - AngularJS 待办事项列表应用程序 - 在页面刷新时保持列表
问题描述
我正在使用 AngularJS 制作一个简单的待办事项列表应用程序。我实际上使用的是 ASP.NET MVC 模板,但到目前为止,我已经成功地通过使用 Angular 和 Bootstrap 来让一切正常工作。
我能够添加和删除任务,并将它们标记为完成。但是,当我刷新页面时,它会重置待办事项列表。刷新页面或导航到网站上的另一个页面时,我需要它来保存列表。该列表仅应在用户关闭浏览器后重置。
我尝试了各种方法,包括 $cookies、$sessionStorage 和 $localStorage,但由于某种原因,我无法让它们中的任何一个工作。在这个阶段,我应该依赖前端进行会话管理,还是后端?
下面是我尝试实现 $localStorage 时的代码示例。我错过了什么吗?
<!DOCTYPE HTML>
<html ng-app="todoApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<body>
<div ng-controller="todoList" class="jumbotron">
<h2><strong>To-Do List</strong></h2>
<br/>
<form ng-submit="addTodo()">
<input type="text" ng-model="todoText"
placeholder="Add new task" size="30">
<button type="submit" class="btn btn-primary glyphicon glyphicon-plus">Add</button>
</form>
<br/>
<ul>
<li ng-repeat="todo in todos">
<label class="checkbox">
<input type="checkbox" ng-model="todo.done">
<span class="done-{{todo.done}}">{{todo.text}}</span>
<span class="glyphicon glyphicon-trash" ng-click="removeTodo()"></span>
</label>
</li>
</ul>
</div>
<script>
var app = angular.module('todoApp', []);
app.controller('todoList', function ($scope, $localStorage) {
$scope.getTodos = function() {
var str = $localStorage.getItem("todos");
$scope.todos = JSON.parse(str);
if (!todos) {
$scope.todos = [{ text: 'Feed the cat', done: true }, { text: 'Mow the lawn', done: false }];
}
}
$scope.saveToDos = function() {
var str = JSON.stringify(todos);
$localStorage.SetItem("todos", str);
}
$scope.addTodo = function () {
if($scope.todoText !== '') {
$scope.todos.push({text:$scope.todoText, done:false});
$scope.todoText = '';
saveToDos();
}
};
$scope.removeToDo = function() {
todos.splice($index, 1);
saveToDos();
}
});
</script>
</body>
</html>
解决方案
$localStorage 不是角度服务,它是一个内置的浏览器功能。
你应该这样使用它:
var jsonObject = {key: 'value'};
window.localStorage.setItem("varName", JSON.stringify(jsonObject)); // this will save "varName" in the local storage with jsonObject as value
jsonObject = JSON.parse(window.localStorage.getItem("varName")); // this will read "varName" from localStorage to jsonObject
推荐阅读
- .net - 如何使用 WcfCoreMtomEncoder .NET 添加标头或请求正文
- authentication - 使用函数在 fetch 中检索令牌
- javascript - js-search 从过滤器选项中排除单词(Laravel 8,PHP/Javascript-Projekt)
- linux - 无法与端口 22 协商:未找到匹配的 MAC。他们的报价:hmac-sha1
- wordpress - 如何将变量从 php 代码传递到 Wordpress 页面
- unity3d - 将 txt 写入 Oculus Quest 2 并在 PC 上读出
- ios - 如何通过单击 UItextfield 以编程方式打开视图以进行选择以进行输入
- python - 从子目录python中提取csv文件
- javascript - 双击可缩放图像返回 100%
- json - 有没有办法将 YAML 文件转换为 Gitlab-ci 文件中的 JSON 文件?