我有一个指令,检查输入的电子邮件是否可用,有效性正常,如果收到电子邮件,我会收到正确的错误消息。如果没有,我没有任何好消息...我的问题只是当验证失败时,键入的电子邮件(当收到电子邮件时)保存在用户范围变量中。当字段为空或电子邮件的格式无效时,情况并非如此(这正是我想要的emailAvailable指令)。你能帮我们解释一下我错过的吗?
Html:
<div class="col-md-12 wow fadeIn">
<div class="md-form">
<div class="md-form">
<input type="text"
name="email"
ng-model="user.email"
ng-pattern="emailFormat"
email-available
required
ng-model-options="{ updateOn: 'blur' }" class="form-control">
<label for="email" class="">Email</label>
<span ng-if="userRegistration.$pending.emailTaken" class="text-success">Vérification....</span>
<div ng-if="userRegistration.$error.emailTaken" class="text-danger">Adresse email déjà prise.</div>
<div ng-show="userRegistration.$submitted || userRegistration.email.$touched">
<div ng-show="userRegistration.email.$error.required" class="text-danger">Vous devez indiquer votre email.</div>
</div>
<div ng-show="userRegistration.email.$error.pattern" class="text-danger">
Votre adresse e-mail n'est pas valide.
</div>
</div>
</div>
</div>
Angular JS
website.directive('emailAvailable', function($timeout, $q, $http, RESOURCE_API) {
return {
restrict: 'AE',
require: 'ngModel',
link: function(scope, elm, attr, model) {
model.$asyncValidators.emailTaken = function() {
return $http({ method: 'POST', url: RESOURCE_API + '/users/checkEmail',
headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, data : {'email': elm.val()} })
.then(function(result) {
$timeout(function(){
model.$setValidity('emailTaken', false);
if (result.data.data.check == 1) {
// Email Taken, Validation Failed
model.$setValidity('emailTaken', false);
} else {
model.$setValidity('emailTaken', true);
}
}, 1000);
});
};
}
}
});
答案 0 :(得分:0)
您未返回被拒绝的承诺,因此模型验证程序不知道验证是否失败。我用$ q做了一个例子。请参阅this plunker.您可以看到该模型对于被拒绝的承诺是空的。
model.$asyncValidators.emailTaken = function(modelValue) {
var deferred = $q.defer();
if(modelValue === 'test') { // Email Taken, Validation Failed
deferred.reject();
} else {
deferred.resolve('success');
}
return deferred.promise;
};
}