2015-04-01 221 views
1

我想過濾products,具體取決於所選的category,可以通過下拉菜單選擇它。 products通過belongsTo category控制器中的過濾器值

Screenshot of the application.

  • 我有什麼在控制器改變取決於下拉菜單中選擇的值來過濾products
  • 如何在下拉菜單中添加空白字段並在選擇時顯示所有產品?

這裏是當前灰燼CLI代碼:

應用程序/路由/ index.js

import Ember from 'ember'; 

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

應用程序/控制器/ 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 /模板/ 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}} 

應用程序/模型/ product.js

import DS from 'ember-data'; 

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

應用程序/模型/ category.js

import DS from 'ember-data'; 

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

回答

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

我怎樣才能在下拉菜單中添加一個空場,並在選擇時,它顯示所有 產品?

在灰燼只需添加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')