I want to bind classes to a div based on a dynamic value in ember; it should hide the DOM element when it is false and add two classes to it when the value is true.
Here is my code:
<div {{bindAttr class="App.User.isLoggedIn:alert alert-error:hide" }} >
...
</div>
However the bindings don’t work and it keeps showing the div even when app.User.isLoggedIn is false.
How do you bind multiple classes based on a true condition?
So, to get a mix of bound attributes (in your case, class names), you can list separate the binding criteria with spaces.
Basically, in your {{bindAttr …}} helper, you can write boundAttr=”criterion1 criterion2 criterion3″, where the individual binding criterion expand out to the following format:
Property substitution
This stubs in classNames with two different behaviours:
Static class/Always true:
Always adds the classname to the div.
Conditional on an property:
Evaluates the property, and assigns the appropriate class based on truthy/falsy values.
In your case, since you want to have two classes hanging off the same property, you could do:
Note the spaces here. The first criterion takes care of just the alert class, while the second takes care of the ‘alert-error’ or ‘hide’ classes accordingly.
If you wanted something even simpler, you could have a calculated property that determines the string you need to apply in your view or model.
Then you could do
And then:
In the hypothetical case where you needed a third, default class for all cases, you could do:
You can read up more on attribute and class bindings in the new ember.js doc, here:
http://emberjs.com/guides/templates/binding-element-class-names/