How to make the angular recognize an ng-keyup event created dynamically in the element

Asked

Viewed 307 times

1

I’m creating a directive that should dynamically include a function in the angular event ng-keyup, I tried to do it this way:

Directive

angular.module('app').directive('validar',validar);

validar.$inject = [];

function validar(){
    var diretica = {
        restrict: 'E',
        require: '?ngModel',
        scope: {
           validador: '&'
        },
        templateUtl: '....html template segue abaixo',[
        link: link  
    };

    return diretiva;


    function link(scope, element, attrs, ngModel) {
        if (scope.validator !== undefined) {
            element[0].setAttribute("ng-keyup", "validador()");
        }     
    }
}

HTML

<input type="text" ng-model="ngModel" />

Problem

I was able to create the attribute in the element, but the angular does not execute the function. When I include the attribute manually in html this way everything works.

<input type="text" ng-model="ngModel" ng-keyup="validador()" />

According to the Honourable Member’s reply, the DOM has already been rendered when my directive dynamically includes the attribute, so the attribute exists in the element, but the angular does not recognize it.

  • 1

    tried using $Scope. $apply() to try to force the angler to update the gift and link the props?

  • @Caiokoiti not yet, I’ll try to do it, thank you!

2 answers

1

This is because he has rederized the final html. You could try twisting instead of ng-keyup add the DOM event itself onkeyup in this way:

function link(scope, element, attrs, ngModel) {
    if (scope.validator !== undefined) {
        element[0].onkeyup = validador();
    }     
}
  • 2

    I did that you said however as onkeyup is not javascript, I realize that I only see the result of the validator function, when there is some update in DOM. That’s why I wanted to use in ng-keyup

1

You can use jquery to catch by placing the code below inside ngOnInit()

import * as $ from 'jquery';   
ngOnInit(){
 $(document).keyup(function(r){
      /* Fazer ação */
    })
}
  • 1

    where would this code stand?

  • 1

    What version of Angular are you using? If it is from angular 2 onwards in . ts of your component.

  • 1

    Even instead of using $(Document) uses the id or name of your input if not at any point in the document it will perform your function.

  • 1

    use the Angularjs

  • 1

    puts, sorry. Maybe you can create another js file and put a $(Document). ready(Function(){ $('#idinput').keyup(Function(r){ /* Do action */ }); }); E do so. jquery should work.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.