18

我有一个异步验证器:

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问题:我希望我的随附表格在承诺未决期间无效。

我知道在异步验证器挂起时使表单无效的两种方法,但它们既冗长又/或笨拙。

// 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它。

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

4

1 回答 1

28

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

<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>
于 2015-05-10T03:36:56.563 回答