当异步验证器承诺挂起时,请考虑表单无效

时间:2014-11-17 17:47:17

标签: angularjs angularjs-model angularjs-ng-form

我有一个异步验证器:

app.directive('validateBar', ['$http', function($http) {
    function link($scope, $element, $attrs, ngModel) {
        ngModel.$asyncValidators.myValidator = function(value) {
            return $http.get('/endpoint/' + value);
        };
    }
    return {
        require: 'ngModel',
        link: link
    };
}]);

表单模板:

<form name="myForm" ng-submit="foo.$valid && saveForm()">
    <input name="bar" ng-model="bar" data-validate-bar>
    <p ng-show="myForm.bar.$error.myValidator">Your bar is wrong</p>
    <button disabled="myForm.$invalid">
</form>

问题:我希望我的随附表单在myValidator承诺待处理时无效。

我知道有两种方法可以在异步验证程序处于挂起状态时使表单无效,但它们都是冗长的和/或hacky。

// Workaround 1: Mark another validator as invalid while the validator promise is pending.
// I cannot mark 'myValidator' as invalid, gets set to valid immediately by Angular.
app.directive('validateSomething', ['$http', function($http) {
    function link($scope, $element, $attrs, ngModel) {
        ngModel.$setValidity('async', false);
        ngModel.$asyncValidators.myValidator = function(value) {
            return $http.get('/endpoint/' + value).then(function() {
                 ngModel.$setValidity('async', true);
            });
        };
    }
    return {
        require: 'ngModel',
        link: link
    };
}]);

<!-- Workaround 2: Prevent submitting through the UI -->
<form name="myForm" ng-submit="myForm.$valid && !myForm.$pending && saveForm()">
    <input name="bar" ng-model="bar" data-validate-bar>
    <p ng-show="myForm.bar.$error.myValidator">Your bar is wrong</p>
    <button disabled="myForm.$invalid || myForm.$pending">
</form>

我不喜欢解决方法1因为我将另一个验证器(async)标记为无效,这可能会产生意想不到的副作用,我不喜欢解决方法2因为我不能再信任{{1}本身。

有谁知道一个干净的解决方案?

0 个答案:

没有答案
相关问题