Reputation: 1974
I am creating a sample todo application in which I can add/remove tasks but when I refresh the page, data is lost. So I decided to use localStorage
to save the task lists and retrieve it when page refreshes.
I am able to do the same but I can retrieve the data only as a array list. How can i list tasks one by one stored in my localStorage
and display it exactly like how it was before page load?
HTML CODE
<body ng-app="todoApp">
<div ng-controller="addTaskController" data-ng-init="init()">
<div class="container">
<h3>ToDo Application</h3>
<div class="form-group col-md-6">
<form ng-submit="addTask()" class="form-inline">
<input type="text" placeholder="Enter Your Task" ng-model="newTask" class="form-control">
<button type="submit" class="btn btn-primary">Add Task</button>
<div class="taskList">
<ol>
<li ng-repeat="task in tasks track by $index">{{task}} <i style="color:red;margin-left:10px;cursor:pointer;" class="fa fa-times" aria-hidden="true" ng-click="deleteTask()" data-toggle="tooltip" title="Delete Task"></i></li>
<p ng-show="tasks.length==0">No Tasks Available </p>
</ol>
</div>
</form>
</div>
</body>
JS CODE
var todoApp = angular.module('todoApp',[]);
todoApp.controller('addTaskController',function($scope){
$scope.tasks = [];
$scope.addTask = function() { // Function to add a task to list
if($scope.newTask == null) {
alert("Please enter a task");
} else {
$scope.tasks.push($scope.newTask);
localStorage.setItem("storedTasks", JSON.stringify($scope.tasks));
$scope.newTask = null;
}; // add() ends
}
$scope.deleteTask = function() {
$scope.tasks.splice(this.$index, 1);
localStorage.removeItem("storedTasks");
};
$scope.init = function() {
$scope.retrievedData = localStorage.getItem("storedTasks");
if($scope.retrievedData != null) {
$scope.tasks.push($scope.retrievedData);
} else {
tasks.length==0;
}
}
});
Before Page Reload
After Page Reload
How can i fix this
Upvotes: 0
Views: 768
Reputation: 691
Since you can only store string
in local storage
, which you did via JSON.stringify()
, you need to undo it via JSON.parse(text[, reviver])
and then iterate over it.
Upvotes: 0
Reputation: 3515
RetrievedData
is an array you have to iterate over and push every item to the tasks
object. What you are doing now is dumping the whole array into a single task.
if($scope.retrievedData != null){
$scope.retrievedData.forEach(function(item){
$scope.tasks.push(item);
})
}
Upvotes: 2