问题
How do I implement multiple filters with checkboxes in emberjs? I would like to filter a grid table with the items that have certain properties that are checked in the template checkboxes...
For example, if I have this fixture:
export default employees[
{
name: 'Ricky',
department: 'Finance',
departmentIsChecked: false
},
{
name:'George',
department:'Marketing'
departmentIsChecked:false
},
{
name:'Jonah',
department: 'Finance',
departmentIsChecked:false
}
];
how would I only display the checked department employees on the table?
This is what I have:
Ember.Controller.extend({
filtered: function(){
var departmentIsChecked = this.get('departmentIsChecked');
var model = this.get('model');
if (departmentIsChecked){
model=model.filterBy('departmentIsChecked', true);
}
return model;
}.property('departmentIsChecked')
});
Template:
{{#each employee in model}}
{{input type='checkbox' checked=employee.departmentIsChecked}}{{employee.department}}
{{/each}}
jsbin: http://emberjs.jsbin.com/gaqavu/10/edit?html,css,js,output
回答1:
If you don't have too many departments, you can create properties that correspond to your department names and then filter your model as follows:
App.EmployeesController = Ember.ArrayController.extend({
inFinance: false,
inMarketing: false,
// ...more departments...
filtered: function(){
var inFinance = this.get('inFinance');
var inMarketing = this.get('inMarketing');
var model = this.get('model');
var newModel = model;
if(inFinance){
newModel = model.filterBy('department', 'Finance');
}
// ... you will need to merge more depts here ...
return newModel;
}.property('inFinance', 'inMarketing')
});
Your template will look something like this:
<script type="text/x-handlebars" data-template-name="employees">
<h3 style='padding:15px'> Filter</h3>
{{input type='checkbox' checked=inFinance}} Finance
{{input type='checkbox' checked=inMarketing}} Marketing
<h2 class="sub-header" >Employees</h2>
<div class="table-responsive">
<table class="table table-hover">
<thead>
<tr>
<th>name</th>
<th>department</th>
</tr>
<tbody>
{{#each employee in filtered}}
<tr>
<td>{{employee.name}}</td>
<td>{{employee.department}}</td>
{{/each}}
</thead>
</script>
Partiall working solution here
来源:https://stackoverflow.com/questions/28179679/how-to-implement-multiple-filters-with-checkboxes-in-emberjs