AngularJS, ngRepeat, and default checked radio button
Asked Answered
M

2

7

When using ngRepeat, 3 pairs of radio buttons can be created using the following code:

<div ng-repeat="i in [1,2,3]">
    <input type="radio" name="radio{{i}}" id="radioA{{i}}" value="A" checked> A
    <input type="radio" name="radio{{i}}" id="radioB{{i}}" value="B"> B
</div>

For some reason, only the last pair of radio buttons generated by ngRepeat is affected by the checked attribute.

Is this because of the way AngularJS updates the view? Is there a way to fix it?

Middle answered 18/12, 2014 at 16:52 Comment(0)
O
13

That is possibly because when browser renders the radio buttons (as ng-repeat expands) all your radios have same name i.e "name="radio{{i}}" angular has not expanded it yet, hence the checked property is not applied properly among all of them. So you would need to use ng-attr-name so that angular adds expanded name attribute later. So try:-

<div ng-repeat="i in [1,2,3]">
    <input type="radio" ng-attr-name="radio{{i}}" ng-attr-id="radioA{{i}}" value="A" checked> A
    <input type="radio" ng-attr-name="radio{{i}}" ng-attr-id="radioB{{i}}" value="B"> B
</div>

Or use ng-checked="true" so that checked attribute is applied as ng-checked directive expands. i.e example

<input type="radio" name="radio{{i}}" ng-attr-id="radioA{{i}}" value="A" ng-checked="true"> A

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>

  
  <div ng-repeat="i in [1,2,3]">
    <input type="radio" ng-attr-name="radio{{i}}" ng-attr-id="radioA{{i}}" value="A" checked> A
    <input type="radio" ng-attr-name="radio{{i}}" ng-attr-id="radioB{{i}}" value="B"> B
</div>
</div>
Ockham answered 18/12, 2014 at 16:57 Comment(3)
Thanks! It should also be noted that, for radio buttons and perhaps other situations, if you're using ngModel, you don't use the checked or ngChecked attributes. Each radio button in a group should have the same ngModel, which contains the value of the radio that should be checked.Middle
@Middle Yup you did not have ng-model in your code.. :)Ockham
Yeah both situations require certain attributes to work out correctly. Your solution fixed one situation I had, and from there, I was able to fix another. Thanks, again!Middle
A
1

Here milestone_data.index == selected cat id;

 <div  ng-repeat="category in catData.categories" > 
 <input type="radio" name="quality" id="{{category.title}}" ng-value="{{category.id}}" ng-model="milestone_data.index" >
  <span>{{category.title}}</span> 
 </div>
Adali answered 13/5, 2016 at 4:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.