Search code examples
radio-buttonaurelia

Aurelia repeater: model.bind is not working for radio buttons


I am creating a set of radio buttons in Aurelia with the code like this:

   <div repeat.for="option of options">
       <input type="radio" id="${option}_id" name="radio_options" model.bind="option" checked.bind="optionValue"/>
       <label for="${option}_id" id="${option}_label">${option}</label>
   </div>

However, doing it this way I discovered that model.bind is not working - the optionValue in corresponding class is not populated when radio button is checked. Similarly when some value is assigned to optionValue in the class, the appropriate radio button is not checked. I found this happening only with repeater. Options are numbers in my case. Could you please help me to find out what may be wrong here?


Solution

  • The first problem is that model.bind should be used when working with objects. Since you're working with a primitive type, you should use value.bind instead.

    The second problem is that input values are always strings, so when setting an initial value, it must be a string. For example:

    Html:

    <template>
      <div repeat.for="option of options">
         <input type="radio" id="${option}_id" name="radio_options" value.bind="option" checked.bind="optionValue"/>
         <label for="${option}_id" id="${option}_label">${option}</label>
       </div>
      <p>Selected Option: ${optionValue} </p>
    </template>
    

    JS:

    export class App {
      options = [ 1, 2, 3, 4 ]
      optionValue = '3';
    }
    

    If you really want to use int in your view-model, you can create a ValueConverter to convert the value to int when passing it to/from the view. For instance:

    export class AsIntValueConverter {
      fromView(value) {
        return Number.parseInt(value);
      }
    
      toView(value) {
        return value.toString();
      }
    }
    

    Usage:

     <input type="radio" id="${option}_id" name="radio_options" value.bind="option" checked.bind="optionValue | asInt"/>
    

    Running Example https://gist.run/?id=1465151dd5d1afdb7fc7556e17baec35