gpt4 book ai didi

javascript - Angular 异步验证器不调用后端

转载 作者:行者123 更新时间:2023-11-28 05:05:06 36 4
gpt4 key购买 nike

我正在尝试制定一个指令,该指令将异步调用我的后端以查看给定客户是否在数据库中,并报告该表单字段是否有效。

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>

我希望输入在 500 毫秒延迟(反跳)后检查任何输入,并对我的后端进行异步调用,以设置该字段无效(如果客户已存在于数据库中)...我什至没有看到 HTTP在我的网络选项卡上进行调用...那么为什么这不起作用???

最佳答案

这是我最终想到的...我认为主要问题是以正确的顺序将 $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>

关于javascript - Angular 异步验证器不调用后端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41818150/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com