Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keydown doesn't properly refresh ng-model in input text but keyup does

I need to retrieve in a directive the value of a text input using ng-model to send value to a data base. If I use in my directive the keydown event, and wrote for exemple 1234 in my input, the result show in my directive is 123, if I wrote abc, the result is ab. If I use keyup, this problem doesn't exist (tested with firefox and chrome). Why does it occur?

My code:

.directive('updateDbb', ["$http", function ($http) {
 return {
 restrict: 'A',
 require: 'ngModel',
  link: function (scope, element, attrs, ngModel) {
        // Listen for change events to enable binding
        var ngModelValue, inputName, testValid, dbbFieldName, idDbb;
        element.bind('keydown', function () {
            ngModelValue = ngModel.$viewValue;
            console.log(ngModelValue); // Show with delay, not the case with "keyup"!!!

...

like image 802
pascal2833 Avatar asked Sep 18 '25 20:09

pascal2833


1 Answers

keydown fires when the user presses on a key, and before the character is being inserted into the input. That's why it doesn't get updated.

keypress fires when an actual character is being inserted in your input. I think it is the event you want to use (if the user maintains the key down, the event will be triggered once for per character inserted)

keyup fires when the user releases a key, after the character has been inserted into the input. (if the user maintains the key down, the event will only be triggered once)

like image 130
Deblaton Jean-Philippe Avatar answered Sep 21 '25 12:09

Deblaton Jean-Philippe