Reputation: 2711
I am needing to add an error class based on two values:
<div {{bind-attr class="anyErrors:errors.email:ui-input--error"}}>
So if anyErrors is true AND errors.email is true it puts the class on the div. I have tried several things but nothing seems to work. Any help is much appreciated.
Upvotes: 1
Views: 2354
Reputation: 395
Just a note that with Ember 1.13 bind-attr
will be deprecated. The correct way going forward will be like this example:
// Using this ember component
Ember.Component.extend({
isValid: true
});
-
{{!-- and this component template --}}
{{!-- these examples would add a 'valid' class to the element --}}
{{!-- if isValid was false, it would fallback to 'invalid', this second "else" string is optional --}}
{{!-- using native html or angle-bracket components (coming soon...) --}}
<div class={{if isValid 'valid' 'invalid'}}></div>
<custom-component class={{if isValid 'valid' 'invalid'}}></custom-component>
{{!-- using sub-expression, useful when using ember input helpers --}}
{{input class=(if isValid 'valid' 'invalid')}}
In the case there you have multiple conditions create them using a computed property. Keep in mind that there are several handy computed property macros, too, that might save you a lot of code (like Ember.computed.and
Ember.computed.or
)
Upvotes: 2
Reputation: 180
You can't put this directly into handlebars(that I'm aware of), however you can easily change the logic in the controller. I would try something like this:
<div {{bind-attr class="hasErrors:ui-input--error"}}>
Then on your controller, have a property hasErrors that checks for anyErrors and error.email are true, like this:
App.IndexController = Ember.ArrayController.extend({
hasErrors: Ember.computed(function(){
return this.get('anyErrors') && this.get('errors.email')
}).property('anyErrors','errors'),
anyErrors: true,
errors: {
email: true
}
});
Try this out and see what happens. The takeaway for what you were originally doing is, if anyErrors was true, it would set the class to errors.email, otherwise it was ui-input--error.
Upvotes: 2
Reputation: 8301
Just use a normal computed property in this case. Ternary form inside of templates is good for simple logic, but gets smelly with multiple conditions.
So:
<div {{bind-attr class="anyErrors:errors.email:ui-input--error"}}>
should be:
<div {{bind-attr class="errorClass"}}>
Now just create your computed property:
errorClass: function () {
return this.get('anyErrors') && this.get('errors.email') ? 'error' : '';
}.property('anyErrors','errors.email')
You can go about this other ways, of course. To me, this is the cleanest pattern.
Upvotes: 4