Madhavan Kumar Madhavan Kumar - 2 months ago 9
AngularJS Question

Angularjs directive - keydown listener is invoked with delay

I have a directive

make-caps
applied to an input element. It will convert all chars in the input box to uppercase as the user types it.

Now, the directive has its event listener attached to
keydown
event.

link : function(scope, element, attrs){
element.bind('keydown', function(event){
//$timeout(function(){
element[0].value = element[0].value.toUpperCase();
//});
})
}


Uppercasing works for all, except that the last character is left out. If user types
elle
, it will render
ELLe
. I am able to fix it by wrapping the code inside
$timeout
block, but i am curious why doesn't the view get updated, when i set
element[0].value


Plunker code is here.

Answer

This is because keydown events are fired before the new character is added to the value of the input. Use keyup

element.bind('keyup', function(event){
    element[0].value = element[0].value.toUpperCase();

})