Reputation: 8318
I want to filter products
depending of the selected category
which can be selected with a drop-down menu. products
belongTo category
products
depending of the chosen value of the drop-down menu?Here is the current Ember CLI code:
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 })
});
Upvotes: 1
Views: 882
Reputation: 35481
What do I have to change in the controller to filter products depending of the chosen value of the drop-down menu?
You could create a computed property that filters the products like:
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?
Just add prompt
value in the Ember select view:
{{view "select" prompt="All products"
content=categories
optionLabelPath="content.name"
optionValuePath="content.name"
value=selectedCategory}}
And then when you observe the selectedCategory
, if the user select's the prompt, the value of the selection will be null
.
Thus you can update the filteredProducts
computed property to take that into account as well:
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')
Upvotes: 4