我正在使用 Angular 1.3.* 并尝试验证我的表单。它在 ng-repeat 中。所以我可能会获得几个输入字段。我不仅要求该字段不为空,而且要求从后台取信息时要搜索成功。
我有这个输入框
<input type="text"
ng-model="user"
placeholder="username"
name="user{{$index}}"
typeahead="data as data.name for data in getUser($viewValue)"
typeahead-editable="false"
class="form-control"
autocomplete="off"
userValidator
required>
<div ng-if="myForm.$submitted" ng-messages="myForm.user{{$index}}.$error ">
<div ng-message="required">You need to type something</div>
</div>
<div ng-if="myForm.$submitted" ng-messages="myForm.user{{$index}}.$error">
<div ng-message="userValidator"> It seems that the entered user is not a valid input</div>
</div>
这是我对 backendCall 的尝试
.directive('userValidator',function($http,$q){
return{
require:'ngModel',
link:function($scope,element,attrs,ngModel){
ngModel.$asyncValidators.userAvailable=function(userInput){
return $http.post('/user'+userInput)
.then(function)????
}
}
}
});
请注意,我希望用户存在。我想我必须使用 asyncValidators 进行后端调用。但是,我似乎不明白。我规避这种情况的一种方法是说,在除“必需”之外的所有其他 $errors 上,显示消息“似乎输入的用户不是有效输入”。我怎样才能成功进行后端调用并使用它,或者,我怎样才能确保在所有其他情况下显示其他错误消息?
最佳答案
如果用户名存在则返回真,如果不存在则拒绝
.directive('userValidator',function($http,$q){
return{
require:'ngModel',
link:function($scope,element,attrs,ngModel){
ngModel.$asyncValidators.userAvailable = function(modelValue , viewValue) {
var userInput= modelValue || viewValue;
return $http.post('/user'+userInput)
.then(function() {
//username exists, this means validation success
return true;
}, function() {
//username does not exist, therefore this validation fails
return $q.reject('selected username does not exists');
});
}
}
}
});
关于javascript - $asyncValidators Angular ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27923529/