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: https://stackoverflow.com/a/18991426/62653
However, it doesn't work when you create the radio buttons dynamically.
This is a snippet from the accepted answer:
<label>
{{view Ember.RadioButton name="selectionTest" selectionBinding="isSelected" value="true"}}
true
</label>
<label>
{{view Ember.RadioButton name="selectionTest" selectionBinding="isSelected" value="false"}}
false
</label>
But when you create the radio button views dynamically like this, it doesn't work:
{{#each myModel.someCollection}}
<label>
{{view Ember.RadioButton name="selectionTest" selectionBinding="isSelected" value=id}}
{{id}}
</label>
{{/each}}
If you use a loop to create the radio buttons as above, the property isSelected
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}}
<label>
{{view Ember.RadioButton name="selectionTest" selectionBinding="isSelected" valueBinding=item.id}}
{{item.id}}
</label>
{{/each}}
And for the curious, here is the original example code for the customized radioButton he is using: http://jsfiddle.net/chopper/CM6fK/35/
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.