gpt4 book ai didi

带有 ng-repeat 验证的 AngularJS 多个表单

转载 作者:行者123 更新时间:2023-12-04 15:44:07 26 4
gpt4 key购买 nike

我使用 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 }"....

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

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

最佳答案

对此的解决方案是创建一个指令来分配 ngModelController每个 ng-repeat 中变量的错误输入。

下面是获取每个子表单错误的可能实现。
DEMO

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 )

请注意字段的结构:
  .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);
}
};
})

关于带有 ng-repeat 验证的 AngularJS 多个表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25180698/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com