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"!!!
...
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With