NicholasJohn16
NicholasJohn16

Reputation: 2409

Dynamically set element id in Ember.js

I have a list of items that I'm loading from a FIXTURES data store:

App.ItemsController = Ember.ArrayController.extend({
    content: function() {
        return App.Item.find();
    }.property('content')
});

App.Item = DS.Model.extend({
    name: DS.attr('string')
});

App.Item.FIXTURES = [
    {id: 1,  name: 'Item 1'},
    {id: 2,  name: 'Item 2'},
    {id: 3,  name: 'Item 3'},
    {id: 4,  name: 'Item 4'},
    {id: 5,  name: 'Item 5'},
    {id: 6,  name: 'Item 6'},
    {id: 7,  name: 'Item 7'},
    {id: 8,  name: 'Item 8'},
    {id: 9,  name: 'Item 9'},
    {id: 10, name: 'Item 10'}
];

and I have a simple template for it

<script type="text/x-handlebars" data-template-name="items">
    <ul>
    {{#each item in content}}
        <li {{bindAttr id="elementId"}} > {{item.name}}</li>
    {{/each}}
    </ul>
</script>

which I'm using {{render 'items'}} to display (for various project specific reasons).

The issue I'm having is that I'd like to dynamically set each li's id to "item-id" where id is the item's id in the model. I've tried every combination of computed property I could think of to set elementId, but I can't get it to work.

Is there a way to do this? Any help would be much appreciated. Thanks.

Upvotes: 1

Views: 4392

Answers (1)

CraigTeegarden
CraigTeegarden

Reputation: 8251

You can set up a computed property in your model and then use that in the bindAttr helper.

App.Item = DS.Model.extend({
  name: DS.attr('string'),
  elementId: function() {
    return "item-" + this.get('id');
  }.property('id')
});

handlebars:

<script type="text/x-handlebars" data-template-name="items">
    <ul>
    {{#each item in content}}
        <li {{bindAttr id="item.elementId"}} > {{item.name}}</li>
    {{/each}}
    </ul>
</script>

JSBin example

Upvotes: 5

Related Questions