过滤控制器中的值

时间:2015-04-01 15:46:05

标签: ember.js ember-cli

我希望根据所选的products过滤category,可以使用下拉菜单选择该productscategory属于products

Screenshot of the application.

  • 根据所选下拉菜单的值,我需要在控制器中更改哪些内容才能过滤import Ember from 'ember'; export default Ember.Route.extend({ model: function() { return { categories: this.store.find('category'), products: this.store.find('product') }; } });
  • 如何在下拉菜单中添加空白字段并在选择时显示所有产品?

这是当前的Ember CLI代码:

应用/路由/ 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')
});

应用/控制器/ index.js

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

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

应用/模板/ index.hbs

import DS from 'ember-data';

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

应用/模型/ product.js

import DS from 'ember-data';

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

应用/模型/ category.js

{{1}}

1 个答案:

答案 0 :(得分:4)

  

我需要在控制器中更改以过滤产品   取决于下拉菜单的选择值?

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

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