I'm making a simple to-do list application using AngularJS. I'm actually using an ASP.NET MVC template, but so far I've managed to get everything working just by using Angular and Bootstrap.
I'm able to add and remove tasks, and mark them as complete. However, when I refresh the page, it resets the to-do list. I need it to save the list when refreshing the page or navigating to another page on the site. The list should only reset after the user closes their browser.
I've attempted various methods, including $cookies, $sessionStorage and $localStorage, but for some reason I can't get any of them to work. At this stage, should I be relying on the front end for session management, or the back end?
Below is an example of my code when I tried to implement $localStorage. Am I missing something?
<!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>