0

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

4

1 回答 1

2

您可以使用括号符号来访问它:

$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>

于 2015-10-27T15:05:46.013 回答