AngularJS,ng重复,默认选中单选按钮

时间:2014-12-18 16:52:54

标签: angularjs radio-button angularjs-ng-repeat ng-repeat

使用ngRepeat时,可​​以使用以下代码创建3对单选按钮:

<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>

出于某种原因,只有ngRepeat生成的最后一对单选按钮受checked属性的影响。

这是因为AngularJS更新视图的方式吗?有办法解决吗?

2 个答案:

答案 0 :(得分:12)

这可能是因为当浏览器呈现单选按钮时(为ng-repeat扩展),所有无线电都具有相同的名称,即"name="radio{{i}}" angular尚未展开它,因此已检查的属性未在所有他们。因此,您需要使用ng-attr-name,以便稍后添加扩展名称属性。所以试试: -

<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>

或者使用ng-checked="true"以便在ng-checked指令扩展时应用checked属性。即示例

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

&#13;
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

此处milestone_data.index ==选择了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>