Directive not being called, custom validator AngularJS

1

I have the following directive:

.directive('validateCPF', function () {
    return {
        require: 'ngModel',
        link: function (scope, element, attrs, ctrl) {

            ctrl.$validators.cpf = function (modelValue, viewValue) {
                console.log('chamou directiva');
                var validatorCPF = new CPF();
                return (validatorCPF.valida(viewValue));
            };
        }
    };
});

This directive uses an external lib to validate cpf , but does not even reach console.log .

My form:

<input id="cpf" class="col-xs-12 cpf" type="text" name="cpf" ng-model="cau.cpf" validate-CPF >
  

Angular VersionJS 1.4

    
asked by anonymous 25.01.2016 / 12:59

1 answer

2

You have some errors in the declaration of your policy. The AngularJS directive is applied through case-sensitive differentiation, and for every capital letter you set in .directive it should be lowercase and preceded by a hyphen in its HTML . See the example:

//No angular
.directive('minhaDiretivaAqui', function () {

//E no seu html
<input minha-diretiva-aqui ...

Remembering that you should not start the name of .directive with a capital letter.

For your policy to work, you should declare it as follows:

//AngularJS
.directive(validateCpf)

//No html
<input validate-cpf

In the way you stated, you would have to call it this way:

<input validate-c-p-f

Complement to the validation, you can call the function only after the user has filled in the CPF value through ng-blur , so when the user finishes typing the CPF, he calls the function and checks it. See:

<input id="cpf" class="col-xs-12 cpf" type="text" name="cpf" ng-model="cau.cpf" validate-cpf ng-blur="verificaCpf(cau.cpf)">


//Na diretiva - Coloque a sua verificação dentro de uma função
scope.verificaCpf = function(valorCpf) {
    //Sua verificação aqui
    ctrl.$validators.cpf = ...
};
    
25.01.2016 / 13:31