Jadiel de Armas Jadiel de Armas - 5 months ago 159
AngularJS Question

Radio button checked by default when using ng-repeat

I have been wanting to have a radio button checked out of a list of radio buttons that I present in the screen using ng-repeat, but my code does not work. This is what I am doing:

<div class="clubRole" data-ng-if="club.checked">
<div data-ng-repeat="role in securityGroups.slice(0,1)">
<input type="radio" class="clubRole" data-ng-model="club.role" data-ng-value="role.securityGroupCode" checked="checked"> {{role.description}}
</div>
<div data-ng-repeat="role in securityGroups.slice(1,securityGroups.length+1)">
<input type="radio" class="clubRole" data-ng-model="club.role" data-ng-value="role.securityGroupCode"> {{role.description}}
</div>
</div>


The intention of the code is to get the first radio button checked, and the others unchecked. That code has a problem: it does not work. But at least it gives the idea of what I am trying to do: I want one of the radio buttons checked by default, no matter which one it is.

Answer

Radio button will be check if the value of the input attribute is equal to the value of modal applied on the radio button.

 <div ng-repeat="val in ['a','b','c']">
     <input
            type="radio"
            name="val"
            data-ng-model="role" 
            data-ng-value="val"
            ng-init="$index==0?(role=val):''"
      />
     {{val}}
 </div>

Checked="checked" will not work in angular context. You can either set the value of radio button explicitly in controller or you can manage it in the view itself as i did in the above example.But the modal should be equate according to the value attribute on the inmput element.

For example if modal is x on three radio button's and each radio button have different value like a,b and c. then x must be equal to any of the value to be checked.

Plunker

Comments