【发布时间】: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 循环。
提前致谢。
【问题讨论】:
-
我发现验证器在表单的加载时触发,而不是在值更改时触发。您是否知道如何仅在更改值时才解雇它们?看我的问题stackoverflow.com/questions/46101820/…
标签: angularjs validation asynchronous directive