具有多个表单字段的角度异步验证

时间:2016-11-25 19:27:33

标签: angularjs validation asynchronous directive

我有一个异步验证指令可以正常工作,但它依赖于两个字段来定义一个人是否存在(numId和type),这里是代码:

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循环。

提前致谢。

2 个答案:

答案 0 :(得分:0)

您可以这样做:

Slatency = 1/[(1-p) + (p/s)]

这样,每当你在$ scope.tipo上有一个新值时,就会调用$ scope.watch。

答案 1 :(得分:0)

事实证明我在ctrl。$ asyncValidators.numId内的错误位置使用了手表,它必须在外面。现在它按预期工作。

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>
相关问题