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
propertyName
This stubs in classNames with two different behaviours:
Static class/Always true:
:className
Always adds the classname to the div.
Conditional on an property:
propertyName:trueClass
propertyName:trueClass:falseClass
propertyName::falseClass
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:
<div {{bindAttr class="App.User.isLoggedIn:alert App.User.isLoggedIn:alert-error:hide"}} >
...
</div>
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
// in your view
classesNeeded: function() {
return App.User.get('isLoggedIn') ? 'alert alert-error' : 'hide';
}.property('App.User.isLoggedIn')
And then:
<div {{bindAttr class="view.classesNeeded"}} >
...
</div>
In the hypothetical case where you needed a third, default class for all cases, you could do:
<div {{bindAttr class=":defaultClass view.classesNeeded"}} >
...
</div>
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With