3

In Ember's input helper, how can I show/hide attributes based on a condition? For example, let's say I want to show required="required" if isEditable is true and disabled="disabled" otherwise. Currently I have something like this:

{{#if isEditable}}
    {{input value=model.name required="required"}}
{{else}}
    {{input value=model.name disabled="disabled"}}
{{/if}}

...but it would be nice if I bind the attributes somehow instead.

Johnny Oshika
  • 54,741
  • 40
  • 181
  • 275

2 Answers2

2

From the EmberJS site

By default, view helpers do not accept data attributes. For example

{{#link-to "photos" data-toggle="dropdown"}}Photos{{/link-to}}

{{input type="text" data-toggle="tooltip" data-placement="bottom" title="Name"}}

renders the following HTML:

<a id="ember239" class="ember-view" href="#/photos">Photos</a>

<input id="ember257" class="ember-view ember-text-field" type="text" title="Name">

There are two ways to enable support for data attributes. One way would be to add an attribute binding on the view, e.g. Ember.LinkView or Ember.TextField for the specific attribute:

Ember.LinkView.reopen({
  attributeBindings: ['data-toggle']
});

Ember.TextField.reopen({
  attributeBindings: ['data-toggle', 'data-placement']
});

Now the same handlebars code above renders the following HTML:

<a id="ember240" class="ember-view" href="#/photos" data-toggle="dropdown">Photos</a>

<input id="ember259" class="ember-view ember-text-field" 
       type="text" data-toggle="tooltip" data-placement="bottom" title="Name">

Or you can reopen the view

Ember.View.reopen({
  init: function() {
    this._super();
    var self = this;

    // bind attributes beginning with 'data-'
    Em.keys(this).forEach(function(key) {
      if (key.substr(0, 5) === 'data-') {
        self.get('attributeBindings').pushObject(key);
      }
    });
  }
});

I typically do the following

<input type="checkbox" {{bind-attr disabled=isAdministrator}}>
blackmind
  • 1,286
  • 14
  • 27
2

{{ input type='text' required=required disabled=disabled }} works just fine

Working example here

There are a whole bunch of attributes that you can bind directly and required and disabled are among the pack. See here

Note @blackmind is correct that if you were to do this from scratch, you would need to do some work. Fortunately though, TextSupport already does the work for you... :) See here

Kalman
  • 8,001
  • 1
  • 27
  • 45