This guide was written for Ember 1.13
So, Ember doesn’t have anything in the way of built-in radio buttons, but there’s a great add-on called ember-radio-button, which you can install via ember-cli:
ember install ember-radio-button
In this particular tutorial, we’ll use ember-radio-button to set up two radio buttons that work as a pair (so only one can be “on” at a time) and set a variable on your controller based on which one the user picks. We will also set one of the radio buttons to be on by default.
Like this:
This guide assumes you already have a template (yourpage.hbs) and a corresponding route (yourpage.js) to work in.
In Ember, adding your code to templates and routes is kind of chicken-and-eggy (where to start?), but I tend to start in the template (.hbs) file.
In your route’s .hbs file
Use the {{#radio-button}} label {{/radio-button}} syntax if you want labels for your radio buttons (which you probably do).
This will give you two side-by-side radio buttons:
{{#radio-button value="vanilla" groupValue=flavor changed="flavorToggled"}} Vanilla {{/radio-button}} {{#radio-button value="chocolate" groupValue=flavor changed="flavorToggled"}} Chocolate {{/radio-button}}
- value is what will get automagically passed to the controller when you click this radio button
- groupValue should match across all radio buttons in the set, or your radio buttons won’t know to un-select themselves when you click a different one
- changed is the action method called when this radio button is clicked
When the user clicks one of these radio buttons, flavorToggled(choice) will be called and the value passed to it as choice will be “vanilla” or “chocolate”.
In your route’s .js file
Add a new action to your action hash. You can call “choice” anything you want (or omit it entirely if you don’t need a passed-in value for whatever reason).
The value that gets passed in here as “choice” was taken from the radio button’s “value” property.
actions: { flavorToggled(choice) { console.log("changing flavor choice", choice); this.controller.set('flavor', choice); } }
If you want one of these radio buttons to be checked by default, you can do that in the setupController in your .js file like so:
setupController() { this.controller.set('flavor', "vanilla"); },
All done!
That’s all there is to it! The documentation that comes with ember-radio-button shows a few more things this tutorial did not cover. Thanks, yapplabs!