2017-04-21 20 views
0

我有一個待辦事項列表,在該列表中我可以檢查它們是否完成。 如果他們完成了,我想用angularJS從我的列表中刪除它們。從angularJS中移除「checked」項數組

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

如果有人能向我解釋這將是太棒了!

+0

你確定*你想從列表中刪除它們,而不是隻標記'done'屬性,然後隱藏它們? – Claies

回答

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

下劃線對我不起作用....「ReferenceError:_未定義」但第一個代碼似乎工作!謝謝 –

+0

對於下劃線,您應該在html中添加腳本 – 2017-04-25 13:07:23

1

你可以存儲你的待辦事項中一個新的數組並清空當前數組中,只加回未做過這樣的事情?:待辦事項

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