提交前验证动态表单 angular

validate dynamic form before submitting angular

我正在使用 ng-repeat 动态创建表单,它们有一些验证属性(简化版):

<div class="row" ng-repeat="defect in model.defects">
    <form name="form_{{defect.id}}" novalidate>
      <input ng-model="defect.name" required/>
      <input type="submit" ng-click="saveDefect(defect)"/>
     </form>
</div>

基本上我想做的是:

$scope.saveDefect = function (defect) {
         if ($scope.<how to get the form name here>.$invalid) {
             return;
         }
}

由于表单名称是使用 ID 动态创建的,我该如何访问它?当然也欢迎使用其他方法来做同样的事情:)

您可以使用 bracket notation 访问它:

$scope["form_"+defect.id]

我建议你做的是:

var app = angular.module("App", []);
app.controller("Ctrl", function($scope) {
  $scope.forms = {};
  $scope.list = [{id: 1}, {id: 2}];
  
  $scope.save = function(item) {
    if ($scope.forms["form_" + item.id].$invalid) {
      alert("error on form_" + item.id);
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="App" ng-controller="Ctrl">
  <div class="row" ng-repeat="item in list">
    <form name="forms.form_{{item.id}}" novalidate>
      <input ng-model="item.name" required/>
      <input type="submit" ng-click="save(item)" />
    </form>
  </div>
</body>