当异步验证器承诺待处理时,将表单视为无效

问题描述 投票:0回答:2

我有一个异步验证器:

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,因为我不再信任
form.$valid
本身。

有人知道干净的解决方案吗?

angularjs angularjs-model angularjs-ng-form
2个回答
28
投票

您可以使用

$pending
来测试某个异步验证器是否在整个表单或特定输入元素上待处理。我还在
$pristine
上添加了一个测试,以在页面加载时隐藏错误消息,并在
ng-disabled
上使用
disabled
而不是
button

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

0
投票
           BIODATA

姓名-Suman Mura,c/o-Nabai Mura,Vill-Sahanui(mallick pur),Post-Rasul Pur,Dist-Purbo Bardhaman,P.S-Memari,Pin No-713151,Education-10 Pass,我的霍比踢足球,

© www.soinside.com 2019 - 2024. All rights reserved.