【发布时间】:2019-01-12 15:21:05
【问题描述】:
我正在使用 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>
【问题讨论】:
-
尝试使用 setItem()(小写 s)
-
$localStorage 不是核心 AngularJS 服务。显示该服务的代码。
-
这段代码sn-p有很多错误。它以找不到
$localStorageProvider开头。然后todos未定义。然后SetItem没有这样的属性。名单还在继续。这段代码 sn -p 对读者没什么用处。
标签: javascript angularjs json asp.net-mvc local-storage