使用复选框和布尔属性触发显示的项目

时间:2015-03-22 08:34:55

标签: ember.js ember-data ember-cli

设置:

ember new shop                                                              
cd shop
ember install:addon ember-cli-scaffold
ember generate scaffold product name:string available:boolean
ember generate adapter product

应用/适配器/ product.js

import DS from "ember-data";

export default DS.FixtureAdapter.extend({});

应用/模型/ product.js

import DS from 'ember-data';

var Product = DS.Model.extend({
  name: DS.attr('string'),
  available: DS.attr('boolean')
});

Product.reopenClass({
  FIXTURES: [
    {
      id: "1",
      name: 'Orange',
      available: true
   }, {
     id: "2",
     name: 'Apple',
     available: false
    }, {
      id: "3",
      name: 'Banana',
      available: true
  }
]});

export default Product;

这将产生以下http://localhost:4200/products页面:

Screenshot of the product index

问题/疑问

我想在http://localhost:4200/products之上添加一个 available 复选框,它会触发显示的产品。如果选中,则仅显示可用的产品。如果未选中仅限不可用的产品。

我该怎么做?什么是最好/最干净的方式?

1 个答案:

答案 0 :(得分:1)

ember g controller products/index

应用/控制器/产品/ index.js

import Ember from 'ember';

export default Ember.Controller.extend({
    products: function(){
      var model = this.get('model');
      var displayAvailable = this.get('displayAvailable') || false;
      return model.filterBy('available', displayAvailable);
    }.property('displayAvailable')
});

app / template / products / index.hbs (前25行)

<h1>Products list</h1>

<p>
  {{link-to "New Product" "products.new" }}
</p>

{{input type="checkbox" checked=displayAvailable }} Display Available Products

{{#if products.length}}
  <table>
    <thead>
      <tr>
        <th>
          Name
        </th>
        <th>
          Available
        </th>
        <th colspan="3">
          Actions
        </th>
       </tr>
     </thead>
     <tbody>
       {{#each product in products}}

enter image description here