AngularJS表单输入名称验证在ngrepeat中不起作用

时间:2016-05-24 19:42:48

标签: javascript angularjs validation angularjs-ng-repeat angularjs-validation

同时在name="number-{{$index+1}}"工作的{p> ng-repeat myform.number-{{$index+1}}.$invalid不适用于表格

演示:http://plnkr.co/edit/Z3EmpHu8w2iZcZko9dJv?p=preview



var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
  $scope.choices = [{no: '1234567890'}, {no: '0987654321'}];
  $scope.numberAdd = function() {
    $scope.choices.push({'no':''});
  };
  $scope.numberRemove = function(item) {
    $scope.choices.splice(item, 1);
  };
});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" />
<script src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9"></script>
<div class="container" ng-app="plunker" ng-controller="MainCtrl">
  <form name="myform" class="form-inline">
    <br>
    <div class="form-group" ng-repeat="choice in choices">
      <div class="input-group">
        <input type="text" class="form-control" ng-model="choice.no" name="number-{{$index+1}}" placeholder="Mobile number {{$index+1}}" required>
        <div class="input-group-addon" ng-if="!$last" ng-click="numberRemove(choice)"><span class="glyphicon glyphicon-minus"></span>
        </div>
        <div class="input-group-addon" ng-if="$last" ng-click="numberAdd()"><span class="glyphicon glyphicon-plus"></span>
        </div>
      </div>
      <span class="text-danger" ng-show="myform.number-{{$index+1}}.$invalid">Field required</span>
    </div>
  </form>
  <br>
  <pre>{{choices | json}}</pre>
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:4)

ng-show接受expression。你可以这样写:

<span class="text-danger" ng-show="myform['number-' + ($index + 1)].$invalid">Field required</span>

更新了演示here

答案 1 :(得分:1)

我添加&#34;跟踪$ index&#34;你的ng-repeat使元素独特,并使用ng-repeat将形式元素移动到div-ng-repeat。无需更改控制器。

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" />
<script src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9"></script>
<div class="container" ng-app="plunker" ng-controller="MainCtrl">
    <div class="form-inline" ng-repeat="choice in choices track by $index" ng-form="myform">
     <div class="form-group">  
        <div class="input-group">
            <input type="text" class="form-control" ng-model="choice.no" name="number" placeholder="Mobile number {{$index+1}}" required>
            <div class="input-group-addon" ng-if="!$last" ng-click="numberRemove(choice)"><span class="glyphicon glyphicon-minus"></span>
            </div>
            <div class="input-group-addon" ng-if="$last" ng-click="numberAdd()"><span class="glyphicon glyphicon-plus"></span>
            </div>
          </div>
          <span class="text-danger" ng-show="myform.number.$invalid">Field required</span>
        </div>
      </div>
  <br>
  <pre>{{choices | json}}</pre>
</div>