Javascript 我可以有条件地退出$asyncValidator吗?
我有一个表单,用户需要输入6个字符。当他输入时,我希望我的指令默认为无效状态$error。输入第6个字符后,将进行API调用,并且只有当6个字符的字符串与后端的条目匹配时,状态才有效。我有以下资料:Javascript 我可以有条件地退出$asyncValidator吗?,javascript,angularjs,angularjs-directive,Javascript,Angularjs,Angularjs Directive,我有一个表单,用户需要输入6个字符。当他输入时,我希望我的指令默认为无效状态$error。输入第6个字符后,将进行API调用,并且只有当6个字符的字符串与后端的条目匹配时,状态才有效。我有以下资料: app.directive("validSectionCode", function ($q, SectionService) { return { require: "ngModel", link: function (scope, element, att
app.directive("validSectionCode", function ($q, SectionService) {
return {
require: "ngModel",
link: function (scope, element, attributes, ngModel) {
ngModel.$asyncValidators.validSectionCode = function (modelValue) {
var promise = SectionService.getSectionByCode(modelValue);
return promise;
}
}
};
});
我的问题是,如果modelValue的长度等于6.据我所知,ngModel.$asyncValidators等待承诺的成功或失败,因此返回true/false在控制台上引起了极大的麻烦。我还尝试将$q.defer.reject作为返回值,但还是出现了错误。如果我想在不执行API调用的情况下使返回无效,那么正确的返回方法是什么?请参见此处的演示
app.directive("validSectionCode", function($q, $http) {
return {
require: "ngModel",
link: function(scope, element, attributes, ngModel) {
ngModel.$asyncValidators.validSectionCode = function(modelValue) {
if (modelValue && modelValue.length == 6) {
return $http.get('/api/users/' + modelValue).
then(function resolved() {
//username exists, this means validation fails
return $q.reject();
}, function rejected() {
//username does not exist, therefore this validation passes
return true;
});
// value length is !=6 validation fails without calling API
} else
{
return $q.reject();
}
}
}
};
});