Removing items from LocalStorage using AngularJS

I am trying to adapt one of the many to-do list examples created using AngularJS and LocalStorage into a small application.

So far I can create and save items in LocalStorage and delete items from both the view and LocalStorage. The problem that I am finding now is that when deleting items, the delete function will not delete the item that I selected, but the first one from the list.

For example, if I have an array of 1-2-3-4, and I choose to delete 3, it will always delete 1 and then 2, etc.

Here is my code, being a beginner, like me, I'm sure I missed something ...

angular.module('Logger', []) .controller('TodoCtrl',['$scope', function($scope){ $scope.todos = extractJSONFromLocalStorage(); $scope.addTodo = function () { $scope.todos.push({ text: $scope.formTodoText}); jsonToLocalStorage($scope.todos); $scope.formTodoText = ''; }; $scope.kill = function (index) { $scope.todos.splice(index, 1); localStorage.removeItem(index); jsonToLocalStorage($scope.todos); }; function extractJSONFromLocalStorage() { return JSON.parse(localStorage.getItem("todo")) || [ {text: 'learn angular', done: false}, {text: 'eat food', done: false}, {text: 'Click to remove', done: true} ]; } function jsonToLocalStorage(todos) { var jsonTodo = angular.toJson(todos); if (jsonTodo != 'null') { localStorage.setItem("todo", jsonTodo); } else { alert("Invalid JSON!"); } } }]); 

And HTML:

  <h1><span class="modal-title">Edit drivers</span></h1> <li ng-repeat="todo in todos"> <span class="done-true">{{todo.text}}</span> <label class="delete pull-right" for='{{todo.text}}' ng-click="kill(index)"> <div><i class="fa fa-close"></i></div> </label> </li> <h2>Add new driver<h2> <form action="" class="form-horizontal controller" ng-submit="addTodo()"> <input class="form-control" type="text" placeholder="Enter driver name" ng-model="formTodoText" ng-model-instant> <button class="btn btn-success form-control">Add</button> </form> 

Any advice would be highly appreciated!

0
angularjs local-storage
source share
1 answer

try putting $index instead of index :

 <label class="delete pull-right" for='{{todo.text}}' ng-click="kill($index)"> 
+3
source share

All Articles