控制器中的过滤值

Filter values in the controller

我想根据所选 category 过滤 products,可以使用下拉菜单进行选择。 products属于category

这是当前的 Ember CLI 代码:

app/routes/index.js

import Ember from 'ember';

export default Ember.Route.extend({
  model: function() {
    return {
      categories: this.store.find('category'),
      products: this.store.find('product')
    };
  }
});

app/controllers/index.js

import Ember from 'ember';

export default Ember.Controller.extend({
  selectedCategory: null,

  categories: function(){
    var model = this.get('model.categories');
    return model;
  },

  products: function(){
    var model = this.get('model.products');
    return model;
  }.property('selectedCategory')
});

app/templates/index.hbs

<p>
{{view "select"
       content=model.categories
       optionValuePath="content.id"
       optionLabelPath="content.name"
       value=selectedCategory
       }}
</p>

{{#each product in products}}
  <li>{{product.name}}</li>
{{/each}}

app/models/product.js

import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr('string'),
  category: DS.belongsTo('category', { async: true }),
});

app/models/category.js

import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr('string'),
  products: DS.hasMany('product', { async: true })
});

What do I have to change in the controller to filter products depending of the chosen value of the drop-down menu?

您可以创建一个计算的 属性 来过滤产品,例如:

filteredProducts: function() {
    var selectedCategory = this.get('selectedCategory');
    var products = this.get('products');
    return products.filter(function(product) {
        return product.get('category.name') === selectedCategory;
    });
}.property('selectedCategory')

How can I add an empty field in the drop-down menu and display all products when it is chosen?

只需在 Ember select 视图中添加 prompt 值:

{{view "select" prompt="All products"
                content=categories
                optionLabelPath="content.name"
                optionValuePath="content.name"
                value=selectedCategory}}

然后当你观察selectedCategory,如果用户select的提示,selection的值将是null

因此您可以更新 filteredProducts 计算的 属性 以将其也考虑在内:

filteredProducts: function() {
    var selectedCategory = this.get('selectedCategory');
    var products = this.get('products');
    if(selectedCategory) { // return filtered products
        return products.filter(function(product) {
            return product.get('category.name') === selectedCategory;
        });
    }
    return products;       // return all products
}.property('selectedCategory')