My keypress event handler is always one keystroke behind and somehow $timeout
fixes this.
<body ng-controller="myController">
<form>
<input ng-keypress="handleKeypress($event)" />
</form>
</body>
Controller:
myapp.controller('myController', function($scope, $timeout){
$scope.handleKeypress = function(ev){
console.log(ev.target.value); //always one keystroke behind
//$timeout(function(){console.log(ev.target.value);}); //works!
};
});
Why is $timeout
necessary and why/how does it work?
I understand that with the keypress
event the character hasn't yet been inserted into the DOM, but I'm confused because the Hello World example at angularjs.org responds before a key is released.
(Their example doesn't use a custom event handler, but clearly Angular is updating the model before the keyup
event, so I'd like understand more about doing this in a custom event handler.)
event.which
is available on keypress
and keydown
, and I thought perhaps Angular might be using String.fromCharCode()
, but I don't see anything in the Angular source to this effect.