Reputation: 479
I'm trying to figure out how to dynamically loop through the DS.attr
's of an Ember-Data Model I've passed into a Component in Ember 2.0. Here's what I have:
Templates:
{{!person-component.hbs}}
{{each-in person as |property value|}}
<tr>
<th>
<td>{{property}}</td>
<td>{{value}}</td>
</th>
</tr>
{{/each-in}}
{{!index.hbs}}
{{person-component person=model}}
Model:
import DS from 'ember-data';
export default DS.Model.extend({
"name": DS.attr('string'),
"height": DS.attr('number'),
"weight": DS.attr('number'),
});
Route:
import Ember from 'ember';
export default Ember.Route.extend({
model() {
return this.store.find('person');
}
});
Is there a simple way to do this from within handlebars? I was thinking possibly that a computed value on the controller might have to do it.
Upvotes: 0
Views: 966
Reputation: 479
Okay, so each-in
isn't designed to magically unbox Ember model attributes, only normal JSON objects. So the solution is to use controller logic which fetches a model's attributes. There might be a better way to do this, but this is the cleanest I've found in my limited experience with Ember.
// app/controllers/person.js
import Ember from 'ember';
export default Ember.Component.extend({
attributes: Ember.computed(function() {
var attrNames = [];
var person = this.get('person');
// Get attributes
person.eachAttribute((name) => attrNames.push(name));
var attrs = Ember.getProperties(person, attrNames);
return attrs;
}),
});
If you implement this with the above code, everything works as expected as long as you modify the template to use attributes
rather than person
.
Upvotes: 1
Reputation: 6153
Your code should work just fine, as long as you are using Ember 2.1 Beta. See the blog post about the new each-in
helper.
http://emberjs.com/blog/2015/08/16/ember-2-1-beta-released.html#toc_code-each-in-code-helper
This helper works exactly as you posted.
Edit
Actually, according to the comments, the get
and each-in
helpers actually snuck into Ember 2.0 (unannounced), see the comment here: http://emberjs.com/blog/2015/08/16/ember-2-1-beta-released.html#comment-2202060073, so no need to use the beta.
Upvotes: 0