1

I have a form with some fields (build with ng-repeat, so I dont know how much). I added to the submit button

ng-disabled=form.field.$invalid

and added to all the fields "required" but the ng-disabled work just for this last field. my code:

 <form name="form" novalidate>

            <div ng-repeat="q in questions">
                 <textarea name="answer" type="text"  ng-model="answers[$index]" required></textarea>


            </div>
            <button ng-disabled="form.answer.$invalid || form.answer.$pristine" type="submit" ng-click="submit(q)">'Submit'</button>
        </form>

how can I validate the user change all fields? thanks!

4

1 回答 1

1

这是因为您的所有输入都具有相同的名称,因此由于表单控制器实例的行为将只有一个具有名称的属性,answers它将指向表单中具有该名称的最后一个 ng-model。ng-attr-name相反,使用可能附加$index和使用表单属性为您的输入提供不同的名称,$invalid只要表单中的 ng-model(s) 之一(带有约束)无效,表单就会无效。因此,只需禁用按钮,直到表单无效,因为它是表单控制器上的一个包罗万象的属性。

<div ng-repeat="q in questions">
  <!-- Provide dynamic form names -->
  <textarea ng-attr-name="answer{{$index}}" type="text" 
            ng-model="answers[$index]" required></textarea>
 </div>
 <!-- Use form.$invalid -->
 <button ng-disabled="form.$invalid || form.$pristine"  
         type="submit" ng-click="submit(q)">Submit</button>

angular.module('app', []).controller('ctrl', function($scope) {
  $scope.questions = ["q1", "q2"]
  $scope.answers = {};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">

  <form name="form" novalidate>

    <div ng-repeat="q in questions">
      <textarea ng-attr-name="answer{{$index}}" type="text" ng-model="answers[$index]" required></textarea>


    </div>
    <button ng-disabled="form.$invalid || form.$pristine" type="submit" ng-click="submit(q)">Submit</button>
  </form>
</div>

于 2014-12-29T21:35:25.470 回答