我希望根据所选的products
过滤category
,可以使用下拉菜单选择该products
。 category
属于products
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}}
答案 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')