表格中有几个字段:
<input name="participant{{$index}}email" type="email" ng-model="participant.email" ng-trim="true"
required ng-minlength="1" ng-maxlength="255"
email-uniqueness-validator="{{$index}}">
我使用emailUniquenessValidator指令检查是否有参与者输入了同一封电子邮件。如果是这样,我显示错误信息:
<div ng-messages="enroll['participant' + $index + 'email'].$error">
<div ng-message="emailUniqueness">The email addresses must be different for every applicant...</div>
</div>
问题是当我有两个具有相同电子邮件的字段时,它们都显示错误。然后用户编辑一封电子邮件,使其与任何其他电子邮件不同,并且该字段上的错误消息按预期消失,但如何通过编辑第一个电子邮件字段从第二个电子邮件字段中删除该错误消息?
指令:
.directive('emailUniquenessValidator',
function() {
return {
require : 'ngModel',
link: function (scope, element, attrs, ngModel) {
scope.$watch(attrs.ngModel, function () {
var currentEmailFieldNo = attrs.emailUniquenessValidator;
var diffEmails = differentEmails(scope, currentEmailFieldNo);
ngModel.$setValidity('emailUniqueness', diffEmails);
if (!diffEmails) {//one field has changed and there is no duplicates, but we need to remove validation errors from the other field
cleanDuplicateEmailErrors(scope);
}
});
}
}
});
differentEmails功能:
function differentEmails(scope, currentEmailFieldNo) {
differentEmails = true;
var currentEmail = currentEmailFieldNo >= 0
? scope.applicantEnrollDto.participants[currentEmailFieldNo].email
: scope.applicantEnrollDto.email;
var mainEmail = scope.applicantEnrollDto.email;
if (currentEmailFieldNo < 0) {
if (emailInArray(currentEmail, scope.applicantEnrollDto.participants)) {
differentEmails = false;
}
} else {
var applicantsNo = scope.applicantEnrollDto.participants.length
var differentEmails = true;
if (applicantsNo) {
differentEmails = !hasDuplicates(scope.applicantEnrollDto.participants);
if (differentEmails) {
if (currentEmail === mainEmail) {
differentEmails = false;
}
}
}
}
return differentEmails;
}
答案 0 :(得分:0)
通过访问范围
中的表单,可以轻松解决问题$scope.form["participant"+i+"email"].$setValidity('emailUniqueness', errorsOff);