Sha
Sha

Reputation: 1974

How to delete an array element stored in local storage

In my simple TODO application i have a array list stored in my local storage. basically it is task lists. while deleting a task i want to delete the same task from local storage as well.

JS Code

  $scope.addTask = function(){
        localStorage.setItem("storedTasks", JSON.stringify($scope.tasks));
  }; //function to add task

  $scope.deleteTask =  function(){ 
    $scope.tasks.splice(this.$index, 1);    
    localStorage.removeItem("storedTasks");
  }; // Function to delete a task from list

HTML

            <div class="taskList">
                <ol>
                    <li ng-repeat="task in tasks track by $index">  {{task}}
                    <i class="fa fa-trash-o" aria-hidden="true" ng-click="deleteTask()" data-toggle="tooltip" title="Delete Task"></i>
                    <i class="fa fa-pencil-square-o" aria-hidden="true" ng-click="editTask()"></i>
                    </li>   
                    <p ng-show="tasks.length==0">No Tasks Available </p>
                </ol>
            </div>

when i use localStorage.removeItem() it clears the entire array rather than the task i wanted to delete. how do i delete only the task which is clicked to be deleted

Upvotes: 1

Views: 1794

Answers (2)

Diksha Tekriwal
Diksha Tekriwal

Reputation: 105

Remove the same task at that index from localstorage using splice function.

$scope.deleteTask =  function(){            
    $scope.tasks.splice(this.$index, 1);    
    $localStorage.storedTasks.splice(this.$index, 1);  
};

Upvotes: 0

Sajal
Sajal

Reputation: 4401

You would need to get item, remove the index value and set the item again.

     $scope.deleteTask =  function(){
        $scope.newTasks = localStorage.getItem("storedTasks");
        $scope.newTasks.splice(this.$index, 1);    
        localStorage.setItem("storedTasks",JSON.stringify($scope.newTasks));
      }; 

Upvotes: 1

Related Questions