我有一个表单,用户需要输入6个字符。在他打字时,我希望我的指令默认为无效状态(一些$ error)。一旦他键入第6个字符,就会进行API调用,只有当6个字符的字符串与后端的条目匹配时,状态才有效。我有以下内容:
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
等待来自promise的成功或失败,所以返回true / false已经在控制台上引发了地狱。我还尝试$q.defer.reject
作为返回值,但同样是错误。如果我想在不执行API调用的情况下使返回无效,那么返回的正确内容是什么?
答案 0 :(得分:0)
请在此处查看演示http://plnkr.co/edit/ujVJslH086ZlwM8xDDUS?p=preview
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();
}
}
}
};
});