等待$ asyncValidators提交表单

时间:2014-12-08 08:39:01

标签: angularjs angularjs-directive

我有一个包含用户名字段和其他字段的表单,此字段有一个异步验证程序,用于在您尝试提交表单时检查该用户名是否可用(表单上的其他字段使用异步验证)。我使用此指令验证并提交表单(仅当它有效时):

<form validation-submit="submit()"></form>
app.directive('validationSubmit', ['$parse', function($parse) {
    return {
        restrict: 'A',
        require: '?form',
        compile: function($element, attr) {
            var submitFn = $parse(attr.validationSubmit);

            return function link(scope, element, attrs, FormController) {
                var submit = function(event) {
                    scope.$apply(function() {
                        if (! FormController.$valid) {
                            return;
                        }

                        submitFn(scope, {$event: event}));
                    });
                };

                element.bind('submit', submit);

                scope.$on('$destroy', function() {
                    return element.off('submit', submit);
                });
            }
        }
    };
}]);

问题是该指令不等待挂起的异步验证完成。如何将此指令更改为仅在完成并传递所有异步验证后提交?

1 个答案:

答案 0 :(得分:1)

最近,我创建了一些检查电子邮件或电话号码是否可用的指令。我找到了帮助我的解决方案。它是$asyncValidators

app.directive('validationSubmit', ['$parse', function($parse) {
    return {
        restrict: 'A',
        require: '?form',
         link: function(scope, element, attrs, FormController) {
                /**
                *returns promise
                **/
                FormController.$asyncValidators.validEmail = function (modelValue) {
                    return $q(function (resolve, reject) { 
                    //Here you should make query to your server and find out wether username valid or not
                    //For example it could be:
                    $http('http://your_api_server/Available').then(function (response) {
                            if (response.data.Available) {
                                resolve();
                            } else {
                                reject();
                            }
                        }, function (err) {
                            reject(err.data);
                        });  
                        });
                };
            }

    };
}]);

您应该在表单中添加属性名称:

<form validation-submit="submit()" name="myForm"></form>

现在您有机会在控制器中检查表单的系统属性:

$scope.submit = function(){
    //Here will be your logic
    if($scope.myForm.$valid ||
       $scope.myForm.$invalid || 
       $scope.myForm.$pending ||
       $scope.myForm.$submitted){
          //do whatever you want
        }
}