角度异步验证器不调用后端

时间:2017-01-24 00:38:32

标签: javascript angularjs

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

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在我的网络标签上发出呼叫......为什么这不起作用?

1 个答案:

答案 0 :(得分:0)

这是我最终想出的......我认为主要的问题是将$ 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>