6

我使用 ng-form 作为父表单和子 mg-forms 以使用 ng-repeat 进行验证。

<div ng-form="form">
    <div ng-repeat="field in fields">
        <div ng-form="subform"><input...></div>
    </div>
</div>

并像这样进行验证:

if ($scope.form.subform.$invalid && !$scope.form.subform.$error.required) {
    // Do something...
}

(这是一个非常简单的例子,对于不同的输入类型和不同的名称,我有更多不同的子表单,例如 input[text] 被命名为 TextForm,input[numeric] 是 NumericForm 等)

如果只有在现场,一切都会按预期工作。但是如果 ng-repeat 生成多个字段,验证只会触发最后一个子表单,其他的会被忽略。

有没有办法循环遍历所有子表单来检查其中一个是否无效?

另外,我正在标记所有未填写的必填字段,如下所示:

if ($scope.form.$error.required) {
     angular.forEach($scope.form.$error.required,
         function (object, index) {
             $scope.form.$error.required[index].$setDirty();
         }
     );
}

因此,如果我的字段是这样完成的:

....ng-form="TextForm" ng-class="{ 'has-error': TextForm.$dirty && TextForm.$invalid }"....

即使有许多同名的子表单,它也会标记所有子表单。

也许我可以对无效字段做类似的事情?虽然尝试了很多东西,但没有任何效果......

4

1 回答 1

2

一个解决方案是创建一个指令,将ngModelController' 错误分配给每个ng-repeat输入中的变量。

下面是一个可能的实现来获取每个子表单的错误。 演示

JAVASCRIPT(指令)

  .directive('ngModelError', function($parse, $timeout) {
    return {
      require: ['ngModel', 'form'],
      link: function(scope, elem, attr, ctrls) {
        var ngModel = ctrls[0],
            ngForm = ctrls[1],
            fieldGet = $parse(attr.ngModelError),
            fieldSet = fieldGet.assign,
            field = fieldGet(scope);

        $timeout(function() {
          field.$error = ngModel.$error;
          field.ngForm = ngForm;
          fieldSet(scope, field);
        });

      }
    };
  });

HTML

<form name="form" ng-submit="submit(form, fields)" novalidate>
  <div ng-form="subForm" ng-repeat="field in fields"
    ng-class="{'has-error': subForm.$invalid && form.$dirty}">
    <label class="control-label">{{field.label}}</label>
    <input type="{{field.type}}" placeholder="{{field.placeholder}}" 
      ng-model="field.model" name="field" 
      ng-required="field.isRequired" class="form-control" 
      ng-model-error="field" />
  </div>
  <br>
  <button type="submit" class="btn btn-primary">Submit</button>
</form>

JAVASCRIPT(控制器)

请注意字段的结构:

  .controller('Ctrl', function($scope) {
    $scope.fields = {
      email: {
        type: 'email',
        placeholder: 'Enter email',
        isRequired: true,
        label: 'Email Address'
      }, 

      password: {
        type: 'password',
        placeholder: 'Enter password',
        isRequired: true,
        label: 'Password'
      }
    };

    $scope.submit = function(form, fields) {
      form.$dirty = true;

      if(form.$valid) {
        // do whatever
      } else {
        // accessing ngForm for email field
        console.log(fields.email.ngForm);
        // accessing errors for email field
        console.log(fields.email.$error);

        // accessing ngForm for password field
        console.log(fields.password.ngForm);
        // accessing errors for password field
        console.log(fields.password.$error);
      }
    };
  })
于 2014-08-07T13:15:18.673 回答