AngularJS:如何验证ng-repeat表单字段

时间:2015-02-08 13:32:44

标签: angularjs

以下代码是我尝试验证表单中的值列表。值位于ng-repeat指令内的表中,应根据需要进行验证。任何输入都将受到赞赏。

<form name="form1">
  <table>
    <tr ng-repeat="param in params">
     <td>
        {{param.name}}
     </td>
     <td>
         <input name="i{{$index}}" ng-model="param.val" required />
         <span style="color:red" ng-show="form1.i{{$index}}.$dirty && form1.i{{$index}}.$invalid">
            <span ng-show="form1.i{{$index}}.required">This field is required</span>
         </span>
       </td>
     </tr>
  </table>
</form>

2 个答案:

答案 0 :(得分:4)

我认为@SunilD&#39; 2对另一个答案的评论值得自己回答,因为ng-form方法可以促进更多验证方案(例如,突出显示表中的一行,其中一个输入无效)

<form name="form1">
  <table>
    <tr ng-repeat="param in params">
     <td>
        {{param.name}}
     </td>
     <td ng-form="cellForm">
         <input ng-model="param.val" required />
         <span ng-show="cellForm.$dirty && cellForm.$invalid">
            <span ng-show="cellForm.$error.required">This field is required</span>
         </span>
       </td>
     </tr>
  </table>
</form>

嵌套ng-form的有效性设置其父表单的有效性。

plunker

答案 1 :(得分:3)

<form name="form1" ng-controller="mycontroller">
  <table>
    <tbody>
      <tr ng-repeat="param in params">
        <td>{{param.name}}</td>
        <td>
          <input name="i{{$index}}" ng-model="param.val" required="" />
          <span style="color:red" ng-show="form1.['i{{$index}}'].$dirty && form1.['i{{$index}}'].$invalid">
            <span ng-show="form1.['i{{$index}}'].required">This field is required</span>
          </span>
        </td>
      </tr>
    </tbody>
  </table>
</form>

工作样本:http://plnkr.co/edit/pxtnW5vzWP8J4KYno3jN?p=preview