Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS, ngRepeat, and default checked radio button

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?

like image 701
user3071284 Avatar asked Dec 18 '14 16:12

user3071284


2 Answers

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>
like image 198
PSL Avatar answered Nov 13 '22 20:11

PSL


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>
like image 28
user2823361 Avatar answered Nov 13 '22 19:11

user2823361