使用AngularJS从LocalStorage中删除项目 [英] Removing items from LocalStorage with AngularJS

查看:157
本文介绍了使用AngularJS从LocalStorage中删除项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将使用AngularJS和LocalStorage构建的许多待办事项列表示例之一适合我的一个小应用程序.

I'm trying to adapt one of the many to-do list examples built with AngularJS and LocalStorage to a little app of mine.

到目前为止,我已经能够创建项目并将其保存到LocalStorage中,并且可以从视图和LocalStorage中删除项目.我现在发现的问题是,当我删除项目时,删除功能不会删除我选择的项目,而是列表中的第一个项目.

So far I'm able to create and save items into the LocalStorage, and to delete items both from the view and the LocalStorage. The problem I'm finding now is that when I delete items, the delete function won't delete the item I chose, but the first from the list.

例如,如果我有一个1-2-3-4数组,而我选择删除3,它将始终删除1,然后是2,依此类推.

For instance, if I have an array of 1-2-3-4 and I choose to delete the 3, it will always delete the 1, and then the 2, and so on.

这是我的代码,是我的初学者,我敢肯定我错过了一些事情...

Here's my code, being a beginner as I am, 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!");
        }
    }
 }]);

和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 tips would be highly appreciated!

推荐答案

尝试将$index代替index:

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

这篇关于使用AngularJS从LocalStorage中删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆