2016-04-25 73 views
0

我正在创建一个示例待办事项应用程序,我可以在其中添加/删除任务,但是当我刷新页面时,数据会丢失。所以我决定使用localStorage保存任务列表,并在页面刷新时检索它。从本地存储器逐一检索数组列表

我能够做到这一点,但我可以检索数据仅作为数组列表。我如何列出存储在我的localStorage中的任务,并将其显示为与页面加载之前的样子完全相同?

HTML代码

<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代码

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; 
      } 
     } 
    }); 

之前重新加载页面

enter image description here

后重新加载页面

enter image description here

我怎样才能解决这个

+0

也可以使用其他方式:'$ scope.tasks = angular.fromJson(localStorage.getItem(“storedTasks”));' – devqon

回答

2

RetrievedData是你必须遍历所有物品推到tasks对象的数组。你现在正在做的是将整个阵列转储到单个任务中。

if($scope.retrievedData != null){ 
    $scope.retrievedData.forEach(function(item){ 
     $scope.tasks.push(item); 
    }) 
} 
相关问题