使用angularJS从数组中删除“checked”项

时间:2017-04-21 10:52:22

标签: angularjs

我有一个带有待办事项的列表,在该列表中我可以检查它们是否完成。 如果他们完成了我想用angularJS从我的列表中删除它们。

<body>
    <h2>Todo</h2>
    <div ng-controller="TodoListController as todoList">
        <span>{{todoList.remaining()}} van de {{todoList.todos.length}} nog te doen</span>
        <ul class="unstyled">
            <li ng-repeat="todo in todoList.todos">
                <label class="checkbox">
                    <input type="checkbox" ng-model="todo.done">
                    <span class="done-{{todo.done}}">{{todo.text}}</span>
                </label>
            </li>
        </ul>
        <form name="formaddtodo" ng-submit="todoList.addTodo()">
            <input type="text" ng-model="todoList.todoText" ng-minlength="1"  size="30"
                   placeholder="Voeg nieuwe todo toe" required>
            <input class="btn-primary" type="submit" value="voeg toe">
        </form>
        <input class="btn-danger" type="button" value="verwijder" ng-click="todoList.removeItem()">
    </div>
</body>

使用removeItem函数我想从列表中删除已检查的项目。

angular.module('todoApp', [])
.controller('TodoListController', function() {
    var todoList = this;
    todoList.todos = [{text:'learn AngularJS', done:false},
        {text:'build an AngularJS app', done:false}];

    todoList.addTodo = function () {
        todoList.todos.push({text: todoList.todoText, done: false});
        todoList.todoText = '';
    };

    todoList.remaining = function () {
        var count = 0;
        angular.forEach(todoList.todos, function (todo) {
            count += todo.done ? 0 : 1;
        });
        return count;
    };

    todoList.removeItem = function() {
        todoList.todos.splice(???)
    }
});

如果有人可以向我解释,那真是太棒了!

2 个答案:

答案 0 :(得分:1)

你可以将你的待办事项存储在一个新的数组中并清空当前的数组并只添加那些没有做过这样的事情吗?

todoList.removeItem = function() {
        var oldTodos = toDoList.todos;
        toDoList.todos =[];
        angular.forEach(oldTodos, function(todo){
            if (!toDoList.todos.done)
              toDoList.todos.push(todo);
          });
    }

答案 1 :(得分:1)

todoList.removeItem = function() {
    angular.forEach(todoList.todo, function(todo, key) {
        if(todo.done)
            todoList.todos.splice(key, 1);
    });
}

您可以使用下划线过滤器

todoList.removeItem = function() {
    todoList.todos = _.filter(todoList.todos, function(todo) { 
        return !todo.done; 
    });
}