Search code examples
ember.jsember-dataember-cli

Trigger displayed items with a checkbox and a boolean attribute


The setup:

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

app/adapters/product.js

import DS from "ember-data";

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

app/models/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;

This will result in the following http://localhost:4200/products page:

Screenshot of the product index

Problem/Question

I'd like to add an available checkbox on top of http://localhost:4200/products which triggers the displayed products. If checked only available products are displayed. If unchecked only unavailable products.

How can I do this? What is the best/cleanest way?


Solution

  • ember g controller products/index

    app/controller/products/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 (the first 25 lines)

    <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