如何检查ngform是否有效

时间:2016-04-15 14:42:44

标签: angularjs angularjs-ng-form

我正在使用ng-repeat动态创建控件,如下所示

<div ng-form="mainform" ng-repeat="usr in users">
    <userdirective ng-form="innerform_idx_{{$index}}></userdirective>
</div>

在我的控制器中我想检查内部表单是否有效。 我在下面尝试过,但它无法正常工作

for(i=0;i<users.length;i++)
{
 var innerformName="innerform_idx_"+i;
  if( $scope.mainform.innerformName.$valid)
   {
    // throwing undefined error.
   }
}

请建议我如何动态检查内部表格的有效性。

谢谢,

1 个答案:

答案 0 :(得分:0)

In my experience, generating a dynamic name for an inner form doesn't work well. However, angular seems to be perfectly fine with having multiple inner forms with the same (static) name.

For validating a single inner form in the controller, you can pass the inner forms validity as a parameter from the view to the controller.

It's also important to know that the parent form will be invalid if any of the child forms is invalid. This can be used for validating all inner forms at the same time.

Code snippet to demonstrate:

var app = angular.module('myapp', []);
app.controller('myctrl', function($scope) {
  $scope.users = ['u1', 'u2', 'u3'];
  $scope.validateForm = function(form) {
    alert('form is valid: ' + form.$valid);
  }
});
.userform {
  margin-bottom: 20px;
}
.invalid {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp" ng-controller="myctrl">
  <div ng-form="parentform">
    <div class="userform" ng-repeat="user in users" ng-form="innerform">
      <div>Username (maximum 5 characters): {{user}}</div>
      <input ng-maxlength="5" ng-model="user" />
      <div ng-class="{'invalid': !innerform.$valid}">inner form is valid: {{innerform.$valid}}</div>
      <button ng-click="validateForm(innerform)">Check my validy in the controller</button>
    </div>
    <div ng-class="{'invalid': !parentform.$valid}">Parent form is valid: {{parentform.$valid}}</div>
  </div>
</div>