andy andy - 25 days ago 4x
Javascript Question

How to bind dynamic radio buttons to controller property in Ember

New to ember so bare with me.

I've been really struggling with radio buttons. I just want to dynamically create some radio buttons and then bind the checked radio button to a property on the controller.

I tried the answer in this question:

However, it doesn't work when you create the radio buttons dynamically.

This is a snippet from the accepted answer:

{{view Ember.RadioButton name="selectionTest" selectionBinding="isSelected" value="true"}}
{{view Ember.RadioButton name="selectionTest" selectionBinding="isSelected" value="false"}}

But when you create the radio button views dynamically like this, it doesn't work:

{{#each myModel.someCollection}}
{{view Ember.RadioButton name="selectionTest" selectionBinding="isSelected" value=id}}

If you use a loop to create the radio buttons as above, the property
doesn't get updated.

Any ideas or other solutions to bind radio buttons?


The scope is being changed inside the #each block to each object in myModel.someCollection. Therefore you are binding the myModel.someCollection.collection.isSelected value. You want to use an alternate form of the #each block which does not change the context, allowing you to bind to isSelected. You also need to explicitly bind the value, which the code you used as a template didn't have to do because the value was hardcoded in. Try this:

{{#each item in myModel.someCollection}}
        {{view Ember.RadioButton name="selectionTest" selectionBinding="isSelected"}}

Here is a working JSFiddle

Here are the docs

And for the curious, here is the original example code for the customized radioButton he is using:

It is worth noting that for these bindings to work correctly, the objects in the array need to be Ember Objects, and they need to be added, removed, and modified using Ember methods only (get and set), which will ensure all the bindings get properly updated.