如何在emberjs中使用复选框实现多个过滤器?

时间:2015-01-27 20:46:23

标签: javascript ember.js checkbox ember-cli

如何在emberjs中使用复选框实现多个过滤器?我想过滤一个网格表,其中的项目具有在模板复选框中检查的某些属性...

例如,如果我有这个装置:

export default employees[
{
  name: 'Ricky',
  department: 'Finance',
  departmentIsChecked: false
},
{
  name:'George',
  department:'Marketing'
  departmentIsChecked:false
},
{
  name:'Jonah',
  department: 'Finance',
  departmentIsChecked:false
}
];

我如何仅在桌面上显示已检查的部门员工?

这就是我所拥有的:

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')
});

模板:

{{#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 个答案:

答案 0 :(得分:1)

如果没有太多部门,您可以创建与部门名称对应的属性,然后按如下方式过滤模型:

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')
});

您的模板将如下所示:

<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>

部分工作解决方案here