etiennenoel
etiennenoel

Reputation: 575

EmberJs add the return string of a function as a class name

Basically, I have an EmberJS Application. In it, I want to show a different validation state and to do so, I want to update the html class attribute. Each of these form elements can have three different names: "" (empty), "has-success" or "has-error".

Basically, I want to bind the class name off a computed property which will return any of those three (much like the AngularJS ng-class) depending on the state of the form.

I want something like this:

validationState: function() {
  if(element.state === "pristine") {
     return "";
  } 
  else if(element.state === "valid") {
     return "has-success";
  }
  else{
     return "has-error";
  }
}

In the template, I would like something like that:

<input class="{{ validationState }} form-control">

Is this something feasible ? If yes, what is the best way to do it ? Creating a custom helper ? Or is there already a way to do so?

Upvotes: 1

Views: 190

Answers (1)

blessanm86
blessanm86

Reputation: 31779

Use the bind-attr helper and make the validationState a computed property. This would look like this

{{input value=inputValue class=validationState}}

App.IndexController = Em.ArrayController.extend({
  inputValue: 'test',
  validationState: function() {
    if(this.get('inputValue')) {
      return 'valid';
    }
    return 'empty';
  }.property('inputValue')
});

Here is a working example.

Upvotes: 2

Related Questions