在提交角度之前验证动态表单

时间:2015-10-27 15:03:46

标签: angularjs angularjs-validation

我使用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动态创建的,我该如何访问它?其他做同样的方式也受到欢迎:)

1 个答案:

答案 0 :(得分:2)

您可以使用bracket notation访问它:

$scope["form_"+defect.id]

我建议你做的是:

&#13;
&#13;
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);
    }
  }
});
&#13;
<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>
&#13;
&#13;
&#13;