【问题标题】:Angular async validation with multiple form fields具有多个表单字段的角度异步验证
【发布时间】:2016-11-25 19:27:32
【问题描述】:

我有一个异步验证指令,它可以正常工作,但它取决于两个字段来定义一个人是否存在(numId 和类型),代码如下:

app.directive('personaUnica', function($http, $q){
return{
    require:'ngModel',
    scope: {
        tipo: "=personaUnica"
    },
    link: function(scope, element, attrs, ctrl){
        ctrl.$asyncValidators.personaUnica = function(modelValue, viewValue){
            if (ctrl.$isEmpty(modelValue)) {
                 // valido si es vacio
                 return $q.when();
            }
            var defer = $q.defer();
            $http.get('/someRESTEndpoint/', {
                params:{ identificacion: modelValue, tipo: scope.tipo }     
            }).then(function(respuesta){
                //Person found, not valid
                if( respuesta.data.elementoExiste ){                        
                    defer.reject('Persona existe.');
                }   
            }, function(respuesta){
                //Person not found, resolve promise
                if(!respuesta.data.elementoExiste){
                    defer.resolve();
                }                       
            });

            return defer.promise;
        }
    }
}
});

但是当其他依赖字段发生变化时,我不知道如何进行相同的验证。

我在指令中读过一些关于 require ^form 的内容,但有点迷路了。

我已尝试添加此代码块

            scope.$watch('tipo', function(){
            ctrl.$validate();   
        }); 

然后我得到一个无限的 $digest 循环。

提前致谢。

【问题讨论】:

标签: angularjs validation asynchronous directive


【解决方案1】:

你可以这样做:

$scope.$watch('tipo', function(newValue, oldValue, scope) {
        if (newValue != oldValue) {
         ctrl.$validate();   
        }
});

这样,每次您的 $scope.tipo 有新值时,都会调用 $scope.watch。

【讨论】:

  • 谢谢卡洛斯,我在错误的地方使用了手表。我发布了答案。干杯。
【解决方案2】:

原来我在 ctrl.$asyncValidators.numId 内的错误位置使用了 watch,它必须在外面。现在它按预期工作。

app.directive('numId', function($http, $q){
return {
    restrict : 'A',
    scope: {
        tipo: "=numId"
    },
    require: 'ngModel',
    link: function(scope, element, attrs, ctrl){
        ctrl.$asyncValidators.numId = function(modelValue, viewValue){              
            if (ctrl.$isEmpty(modelValue) || ctrl.$isEmpty(scope.tipo)) {
              // consider empty model valid
              console.log('Not going yet..');
              return $q.when();
            }

            var defer = $q.defer();

            $http.get("/some-server/endpoint",{
                params:{ identificacion: modelValue, tipo: scope.tipo }     
            }).then(function(res){                                      
                if( res.data.personaExiste){
                    console.log('exists, not valid')                        
                    defer.reject('exists, not valid');
                }else if( !res.data.personaExiste ){
                    console.log('NOT exists, valid!')                       
                    defer.resolve();
                }   
            }, function(){
                defer.reject('Error...');
            });

            return defer.promise;                   
        }

        // Search when tipo is changed
        scope.$watch('tipo', function(){
            console.log('Tipo:' + scope.tipo)       
            ctrl.$validate();   
        });             
    }
}
});

还有html:

<div class="form-group">
   <label>Numero identificacion</label>
   <input type="text" 
          name="numId"
          required
          ng-model="busqueda.numId"                     
          num-id="busqueda.tipoUsuario">
    <pre class="well"> {{ frmBuscar.numId.$error }} </pre>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-18
    • 1970-01-01
    • 2020-01-17
    • 2018-02-21
    • 1970-01-01
    • 2019-07-08
    • 2013-09-12
    • 2018-06-17
    相关资源
    最近更新 更多