【问题标题】:Filter values in the controller过滤控制器中的值
【发布时间】:2015-04-01 15:46:04
【问题描述】:

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

  • 我必须在控制器中进行哪些更改才能根据下拉菜单的所选值过滤products
  • 如何在下拉菜单中添加一个空白字段并在选择时显示所有产品?

这是当前的 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 })
});

【问题讨论】:

    标签: ember.js ember-cli


    【解决方案1】:

    我必须在控制器中进行哪些更改才能过滤产品 取决于下拉菜单的选择值?

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

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

    如何在下拉菜单中添加一个空字段并显示所有 什么时候选的产品?

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

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

    然后当你观察selectedCategory时,如果用户选择的提示,选择的值将是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')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-11
      • 2014-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-28
      • 1970-01-01
      相关资源
      最近更新 更多