Search code examples
cssember.jsember-controllers

set CSS class depending on returned string with Ember


Im still learning ember and i didn't got how i can apply certain CSS class depending on the returned string of a model on a certain controller.

The official documentation (http://emberjs.jsbin.com/yoqifiguva/1/edit?html,js,output) only covers when you have a boolean.

I didn't manage to apply this knowledge for my case. I have status string string like : "passed", "failed", "pendent" and "blocked", which i want to apply different css class for each status.

Any examples on how to achieve that?


Solution

  • You can use bind-attr, for example:

    <ul>
    {{#each item in model}}
      <li {{bind-attr class='item.status'}}>An item with status: `{{item.status}}`</li>
    {{/each}}
    </ul>
    

    Which produces following HTML:

    <ul>
      <li class="passed" data-bindattr-262="262">An item with status: `passed`</li>
      <li class="failed" data-bindattr-265="265">An item with status: `failed`</li>
    </ul>
    

    For collection:

    [
      YourModel.create({ status: 'passed'}),
      YourModel.create({ status: 'failed'})
    ]
    

    of objects declared like:

    YourModel = Em.Object.extend({
      status: null
    });
    

    Demo.

    You can also create Component which can be reused with many models. Component code:

    App.StatusItemComponent = Em.Component.extend({
      classNameBindings: ['status'],
    
      status: function() {
        var modelStatus = this.get('model.status');
        if (modelStatus)
          return 'status-' + modelStatus;
      }.property('model.status')
    });
    

    Template code:

    {{#each item in model}}
      {{#status-item model=item}}
        An item with status: {{item.status}}
      {{/status-item}}
    {{/each}}
    

    Demo.