Reputation: 3617
I have the following in my routes
import Ember from 'ember';
export default Ember.Route.extend({
model: function() {
return this.store.query('post',{published:true});
}
});
and a post-viewer component that renders the model. the problem that i am facing with is filter
. How can i implement the same without loading the models each time. Currently i am just passing the models in the component and using the following
{{#each posts as |item|}}
{{/each}}
To render the elements. What is the proper way by which lets say i can filter them based on title containing some specific keyword. I tried using this.store.query
inside the each loop but that did not work out.
Upvotes: 0
Views: 378
Reputation: 18240
If you use this.store.query
ember does not cache the result. So probably you should use a .findAll()
and then filter the data on the client side. A simple way to do so is inside your model()
hook:
return this.store.findAll('post')
.then(posts => posts.filter(post => get(post, 'published') === true));
This will work because ember-data does cache the result of the findAll()
and the filter executes on the client. You can do the same with a computed property. This has some benefits, as, for example, you can filter based on another property. A computed property in your controller for example:
filteredModel: Ember.computed('[email protected]', 'searchName', {
get() {
return get(this, 'model').filter(record => get(record, 'name') === get(this, 'searchName'));
}
});
Upvotes: 1
Reputation: 7169
You can use
https://github.com/DockYard/ember-composable-helpers
filter -Filters an array by a callback.
{{#each (filter (action "isActive") users) as |user|}}
{{user.name}} is active!
{{/each}}
filter-by Filters an array by a property.
{{#each (filter-by "isActive" true users) as |user|}}
{{user.name}} is active!
{{/each}}
If you omit the second argument it will test if the property is truthy.
{{#each (filter-by "address" users) as |user|}}
{{user.name}} has an address specified!
{{/each}}
You can also pass an action as second argument:
{{#each (filter-by "age" (action "olderThan" 18) users) as |user|}}
{{user.name}} is older than eighteen!
{{/each}}
P.S. Another variant ( pure Ember.js ) - create computed property and iterate over it. And inside computed property filter items
Upvotes: 0