Angularjs 具有多个表单字段的角度异步验证
我有一个async validation指令,该指令在以下情况下可以正常工作,但它取决于两个字段来定义人员是否存在(numId和type),下面是代码:Angularjs 具有多个表单字段的角度异步验证,angularjs,validation,asynchronous,directive,Angularjs,Validation,Asynchronous,Directive,我有一个async validation指令,该指令在以下情况下可以正常工作,但它取决于两个字段来定义人员是否存在(numId和type),下面是代码: app.directive('personaUnica', function($http, $q){ return{ require:'ngModel', scope: { tipo: "=personaUnica" }, link: function(scope, element, attrs,
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循环
提前感谢。您可以这样做:
$scope.$watch('tipo', function(newValue, oldValue, scope) {
if (newValue != oldValue) {
ctrl.$validate();
}
});
这样,每当您在$scope.tipo上有一个新值时,$scope.watch就会被调用。结果表明,我在ctrl中的错误位置使用了watch。$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>
数字识别
{{frmBuscar.numId.$error}
谢谢卡洛斯,我把手表用错地方了。我张贴了答案。干杯。我发现验证器是在表单加载时启动的,而不是在值更改时启动的。你有没有想过只有在你改变价值的时候才能发射它们?看到我的问题了吗