在bind-attr中基于多个条件添加类

时间:2014-08-11 18:22:12

标签: ember.js

我需要根据两个值添加错误类:

<div {{bind-attr class="anyErrors:errors.email:ui-input--error"}}>

因此,如果anyErrors为true且errors.email为true,则将该类放在div上。我尝试了几件事似乎没什么用。非常感谢任何帮助。

3 个答案:

答案 0 :(得分:4)

在这种情况下,只需使用普通的计算属性。模板内部的三元形式对于简单的逻辑很有用,但在多种条件下会变臭。

所以:

<div {{bind-attr class="anyErrors:errors.email:ui-input--error"}}>

应该是:

<div {{bind-attr class="errorClass"}}>

现在只需创建您的计算属性:

errorClass: function () {
  return this.get('anyErrors') && this.get('errors.email') ? 'error' : '';
}.property('anyErrors','errors.email')

当然,你可以采用其他方式。对我来说,这是最干净的模式。

答案 1 :(得分:2)

你不能将它直接放入把手(我知道),但你可以轻松改变控制器中的逻辑。我会尝试这样的事情:

<div {{bind-attr class="hasErrors:ui-input--error"}}>

然后在你的控制器上,有一个属性hasErrors来检查anyErrors并且error.email是真的,如下所示:

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
  }
});

尝试一下,看看会发生什么。你最初做的事情是,如果anyErrors为真,它会将类设置为errors.email,否则它是ui-input - 错误。

答案 2 :(得分:2)

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)

相关问题