首页 > 解决方案 > 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>

标签: javascriptangularjsjsonasp.net-mvclocal-storage

解决方案


$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

推荐阅读