我正在尝试创建一个指令,该指令将异步调用我的后端,以查看给定的客户是否已经在数据库中,并报告该表单域是否有效。
function getCustomerValidationDirectiveFunc(){
return {
restrict: "A",
require: "ngModel",
link: function(scope, element, attr, ngModel){
var serverAddr = '/validate/customer/'
ngModel.$validators.invalidUsername = function(modelValue, viewValue) {
// validation logic here
var username = modelValue || viewValue;
var deferred = $q.defer();
// ask the server if this username exists
$http.get(serverAddr+username).then(
function(response) {
console.log("RESPONSE RECEIVED FROM SERVER")
if (response.data.exists) {
deferred.reject();
} else {
deferred.resolve();
}
});
// return the promise of the asynchronous validator
return deferred.promise;
}
}
}
}
app.directive('customerValidator', ['$http', '$q', getCustomerValidationDirectiveFunc()]);下面是我的HTML代码:
<p><input type="text" ng-model="customer.customer_id" required customer-vlidator ng-model-options="{updateOn: 'default blur', debounce: {default: 500, blur: 0}}"></input></p>我希望输入在500ms延迟(去抖动)后检查任何输入,并对我的后端进行异步调用,以便在客户已经存在于数据库中的情况下将该字段设置为无效...我甚至没有在我的网络选项卡上看到HTTP调用...那么为什么这不起作用?
发布于 2017-01-24 16:55:21
这是我最后想到的.我认为主要的问题是以正确的顺序将$q传递给函数。($q.defer不是函数)以及$http.get().then()回调中的if语句。它是response.data.exist,我将其更改为response.data === false,并从我的验证端点返回true或false。
JAVASCRIPT
app.directive('customerValidator', ['$q','$http', function($q, $http){
return {
restrict: "A",
require: "ngModel",
link: function(scope, element, attr, ngModel){
var serverAddr = '/validate/customer/'
ngModel.$asyncValidators.invalidCustomer = function(modelValue, viewValue) {
// validation logic here
var customer = viewValue || modelValue;
var deferred = $q.defer();
// ask the server if this username exists
$http.get(serverAddr+customer).then(
function(response) {
if (response.data === false) {
deferred.reject();
} else {
deferred.resolve();
}
});
// return the promise of the asynchronous validator
return deferred.promise;
}
}
}}]);HTML
<input type="text" ng-model="customer.customer_id" required customer-validator ng-model-options="{updateOn: 'default blur', debounce: {default: 500, blur: 0}}"></input>https://stackoverflow.com/questions/41818150
复制相似问题