Yaniv De Ridder
Yaniv De Ridder

Reputation: 783

Ember.js binding a css style in a template

This is solved since Ember 1.8 with the HTMLBars engine.

I would like to bind a css style in a template. What would be the solution ?

I tried this:

<div class="bar" style="width:{{barWidth}}px"></div>

but DOM element look like this after its been rendered:

<div class="bar" style="width:<script id='metamorph-28-start' type='text/x-placeholder'></script>5.000000000000002<script

id='metamorph-28-end' type='text/x-placeholder'>px">

Obviously here we can see that the tag for metamorph was added within the style attribute...

I'm wondering what is the best way to achieve such things with Ember.js


There is something i don't get yet.

I have a template as follow:

<script type="text/x-handlebars" data-template-name="listTemplate">
<ul id="list">
    {{#each App.list}}
      <li {{bindAttr data-item-id="itemId"}}>
        <div>
            <span class="label">{{itemName}}</span>
            <div class="barContainer">
              <div class="bar" {{bindAttr style="barWidth"}}></div>   
              <div class="barCap"></div>
            </div>
        </div>
      </li>
    {{/each}}
    </ul>

i'm in a for each loop that loops thru my ArrayProxy content... and the bar width vary depending of the value of each item in the list. Your solution here will not work as the view is the UL and i need a barWidth per model item. and I do not want to polute my Model with css related things like "width: ###px"

Is there any other elegant way to solve what i try to do ? maybe it would be radically different. I'm very new to ember.js and try to discover the best-practices yet:)

Upvotes: 20

Views: 13602

Answers (4)

Daniel
Daniel

Reputation: 18682

In Ember 2.0:

<div class="bar" style="width:{{barWidth}}px"></div>

will just work.

Upvotes: 1

Tom Whatmore
Tom Whatmore

Reputation: 1327

Set a string on your view that looks like "width: 100px" and then bind it to your div with the bind-attr helper like so: <div {{bind-attr style="divStyle"}}>Test</div>

http://jsfiddle.net/tomwhatmore/rearT/1/

Upvotes: 15

Bogdan M.
Bogdan M.

Reputation: 1128

Add unbound:

<div class="bar" style="width:{{unbound barWidth}}px"></div>

Upvotes: 11

Yaniv De Ridder
Yaniv De Ridder

Reputation: 783

To simplify all that, I created a tiny handlebars helper for emberjs that allows you to bind any style properties. You can look at https://github.com/yderidde/bindstyle-ember-helper

Upvotes: 14

Related Questions