Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding classes to a div in ember

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?

like image 466
AbdulFattah Popoola Avatar asked Dec 26 '22 13:12

AbdulFattah Popoola


1 Answers

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:

  1. if the property value is a boolean: the dasherized property name
  2. if the property value is a string: the string value

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/

like image 96
Gopherkhan Avatar answered Dec 29 '22 02:12

Gopherkhan