AngularJS, ngRepeat, and default checked radio but

2020-03-16 07:11发布

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?

2条回答
Emotional °昔
2楼-- · 2020-03-16 07:16

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>
查看更多
劳资没心,怎么记你
3楼-- · 2020-03-16 07:25

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>

查看更多
登录 后发表回答