我从另一方面找到了这个本地存储代码,但是我试着把它放在我自己的代码上,这不起作用。如果我刷新我的网站,我可以看到待办事项列表的编号,但它自己的列表已经消失了吗?
有人如何解释我,有什么不对? :)
顺便说一下,我的控制器在我的起始身体标签上:
<main>
<h1>What to do today?</h1>
<div class="container">
<span>{{ remaining() }} of {{ todos.length }} remaining</span>
<form ng-submit="addTodo()">
<input type="text" ng-model="todoInput" placeholder="Add a new todo" required>
<input type="submit" value="Add new list" >
</form>
<ul>
<li ng-repeat="todo in todos">
<input type="checkbox" ng-model="todo.done">
<span ng-bind="todo.todoText"></span>
</li>
</ul>
<button ng-click="remove()">Clear completed</button>
</div>
</main>
<footer>
<div layout="row" layout-align="center center">
<h3>Winkel Design a/s</h3>
</div>
</footer>
<script>
var app = angular.module('TodoApp', []);
app.controller('todoCtrl', function($scope) {
$scope.saved = localStorage.getItem('todos');
$scope.todos = (localStorage.getItem('todos')!==null) ? JSON.parse($scope.saved) : [{todoText:'Clean your room', done:false}];
localStorage.setItem('todos', JSON.stringify($scope.todos));
$scope.addTodo = function() {
$scope.todos.push({todoText:$scope.todoInput, done:false});
$scope.todoInput = "";
localStorage.setItem('todos', JSON.stringify($scope.todos));
};
$scope.remove = function() {
$scope.todos = $scope.todos.filter(function(item){
return !item.done
});
};
$scope.remaining = function() {
var count = 0;
angular.forEach($scope.todos, function(todo){
count+= todo.done ? 0 : 1;
});
return count;
};
$scope.archive = function() {
var oldTodos = $scope.todos;
$scope.todos = [];
angular.forEach(oldTodos, function(todo){
if (!todo.done)
$scope.todos.push(todo);
});
localStorage.setItem('todos', JSON.stringify($scope.todos));
};
});
</script>
</body>
答案 0 :(得分:0)
看来,除ng-repeat
指令外,您的代码工作正常。我必须添加track by $index
,就我所见,现在一切正常。
<li ng-repeat="todo in todos track by $index">
<input type="checkbox" ng-model="todo.done">
<span ng-bind="todo.todoText"></span>
</li>
来自docs:
如果您确实需要重复重复项目,则可以使用跟踪表达式替换默认跟踪行为。
例如,您可以使用特殊范围属性$ index:
按集合中每个项目的索引跟踪项目。
此外,我建议您使用角度模块,如angular-local-storage
,它将回退到cookie,以防浏览器不支持localStorage API。