尝试学习Angular并遇到一次删除多个对象的问题。我正在创建一个待办事项应用,当用户勾选多个项目并点击"清除已完成"按钮希望检查的项目被删除,剩余的项目留下来。
目前我可以添加,删除单个项目以及编辑项目。我想要做的是点击带有复选框的多个项目,然后根据done:true
问题:
如何浏览每个项目并查看<span class="item-display done-{{items.done}}">{{items.title}}</span>
是否为TRUE并删除具有clear()
功能的项目?
Angular Version:1.3.15
目录设置:
|-index.html
|-js/
|app.js
|todo.ctrl.js
HTML:
<body ng-app="app">
<section class="module" ng-controller="todoController as todo">
<div class="container">
<h1>{{todo.title}}</h1>
<form name="todo.addForm" class="form" ng-submit="todo.addItem()">
<div class="form-group">
<label>Add New Item</label>
<input type="text" class="form-control" ng-model="todo.new.title" required />
</div>
<button class="btn btn-primary pull-right"><span class="glyphicon glyphicon-plus-sign"> Add</span></button>
</form>
<h3>Items:</h3>
<ul class="list-group">
<li class="list-group-item todo-item" ng-repeat="items in todo.items">
<input type="checkbox" ng-model="items.done"/>
<span class="item-display done-{{items.done}}">{{items.title}}</span>
<form>
<input class="form-control" type="text" ng-model="items.title" ng-keyup="todo.editOnEnter($index)"/>
</form>
<a ng-click="todo.delete($index)">Delete</a>
<a ng-click="todo.toggleEditMode($index)">Update</a>
</li>
</ul>
<button class="btn btn-danger pull-right" ng-click="todo.clear()">Clear Completed</button>
</div>
</section>
<script src="bower_components/jquery/dist/jquery.min.js"></script>
<script src="bower_components/angular/angular.min.js"></script>
<script src="js/app.js"></script>
<script src="js/todo.ctrl.js"></script>
app.js:
angular.module('app', []);
todo.ctrl.js:
angular.module('app').controller("todoController", function(){
var vm = this;
vm.title = 'To Do Application';
vm.input = '';
vm.items = [{
title : 'dog food',
done : false
}];
vm.new = {
title : '',
done: false
};
vm.addItem = function(){
vm.items.push(vm.new);
vm.new = {title:'',done: false};
};
$(document).click(function(){
console.log(vm.items);
});
vm.delete = function (index){
vm.items.splice(index, 1);
};
vm.update = function(index){
vm.items.copy(index, 1);
};
vm.toggleEditMode = function(){
$(event.target).closest('li').children('.item-display, form').toggleClass('editing');
};
vm.editOnEnter = function(index){
if(event.keyCode == 13){
vm.toggleEditMode();
}
};
//
//
// NEED HELP HERE
//
//
vm.clear = function(){
var oldTodos = vm.items;
//vm.items = [];
angular.forEach(oldTodos, function() {
if (vm.items.done == true){
this.remove();
}
});
};
});
答案 0 :(得分:3)
我不完全确定我是否理解您的问题,但如果我没有弄错,您想要从列表中清除done
todos吗?
Array.prototype.filter函数将根据过滤函数修剪数组。如果你返回true,它将保留该项,如果你返回false,它将删除它。
vm.clear = function(){
vm.items = vm.items.filter( function( item ){
return !item.done
}
}