【发布时间】:2014-01-17 19:19:28
【问题描述】:
我完全不明白为什么我的按键事件处理程序总是落后一键。 http://plnkr.co/edit/w3FAXGd5zjrktO6DgOpD?p=preview
<body ng-controller="myController">
<form>
<input ng-keypress="handleKeypress($event)" />
</form>
</body>
控制器:
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!
};
});
为什么需要 $timeout 以及它为什么/如何工作? (最好是新手友好的答案)
我知道对于 keypress 事件,字符尚未插入 DOM,但我很困惑,因为 angularjs.org 的 Hello World 示例在释放键之前响应。他们的示例没有使用自定义事件处理程序,但显然 Angular 在 keyup 事件之前更新模型,所以我想了解更多关于在自定义事件处理程序中执行此操作的信息。
idursun 的回答指出 event.which 可在按键上使用,我认为 Angular 可能正在使用 String.fromCharCode(),但我在 Angular 源代码中没有看到任何关于此效果的内容。
【问题讨论】:
标签: angularjs angularjs-directive