角度ng-repeat内的单选按钮组验证

时间:2016-07-29 04:20:50

标签: angularjs radio-button radiobuttonlist

我正在尝试在角度重复中实现单选按钮组验证。

HTML

Child1
Child2

每次重复都应更改名称属性。我尝试附加$ index值,但在动态添加和删除驱动程序时它无法正常工作。实现这个的最佳方法是什么?

4 个答案:

答案 0 :(得分:0)

在您的代码中,所有单选按钮都会相互关联,因为all的name属性是相同的。您应该识别每个单选按钮组。例如:

<div ng-repeat="driver in drivers">
   <input required type="radio" value="M" name="driverGender[{{driver.id}}]" ng-model="driver.gender">
   <input required type="radio" value="F" name="driverGender[{{driver.id}}]" ng-model="driver.gender">
</div>

答案 1 :(得分:0)

您可以根据索引值更改名称属性,可以在以下链接中查看我的答案

在控制器中

 $scope.drivers = [{id:1,name:'test',gender:'M'}];

在html中

<div ng-repeat="driver in drivers">
  <input required type="radio" value="M" name="driverGender{{$index}}" ng-model="driver.gender">
  <input required type="radio" value="F" name="driverGender{{$index}}" ng-model="driver.gender">
</div>

https://plnkr.co/edit/byLRBhUI2Ezc5CofHnPC?p=preview

答案 2 :(得分:0)

试试这个如果您需要以下

认为他们是模型中的两个重复,那么视图的代码应该是这样的

<div ng-repeat="driver in drivers" class="ng-scope">
   <input required="" type="radio" value="M" name="driverGender0" ng-model="driver.gender"/>
   <input required="" type="radio" value="F" name="driverGender0" ngmodel="driver.gender">
</div>
<div ng-repeat="driver in drivers" class="ng-scope">
   <input required="" type="radio" value="M" name="driverGender1" ng-model="driver.gender"/>
   <input required="" type="radio" value="F" name="driverGender1" ngmodel="driver.gender"/>
</div>

所以这是获取此代码的代码

<div ng-repeat="driver in drivers">
   <input required type="radio" value="M" name="driverGender{{$index}}" ng-model="driver.gender">
   <input required type="radio" value="F" name="driverGender{{$index}}" ngmodel="driver.gender">
</div>

答案 3 :(得分:0)

最后我找到了一个解决方案。

<div ng-repeat="driver in drivers">
   <div ng-form="radioForm">
      <input required type="radio" value="M" name="driverGender{{$index}}" ng-model="driver.gender">
      <input required type="radio" value="F" name="driverGender{{$index}}" ngmodel="driver.gender">
      {{radioForm.$error}}
   </div>
</div>

现在通过ng-form进行验证。单选按钮将被分组,因为$ index。