【问题标题】:Keydown doesn't properly refresh ng-model in input text but keyup doesKeydown 不能正确刷新输入文本中的 ng-model 但 keyup 可以
【发布时间】:2015-09-22 13:42:21
【问题描述】:

我需要在指令中检索文本输入的值,使用 ng-model 将值发送到数据库。 如果我在指令中使用 keydown 事件,并在输入中写入示例 1234,则指令中显示的结果为 123,如果我写 abc,则结果为 ab。 如果我使用 keyup,则不存在此问题(用 firefox 和 chrome 测试)。 为什么会发生?

我的代码:

.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 是 keypress 事件的第一部分。 keydown是字符输入完成,然后绑定值。

标签: angularjs keydown


【解决方案1】:

keydown 在用户按下某个键并且在字符被插入输入时触发。 这就是它没有更新的原因。

keypress 在您的输入中插入实际字符时触发。我认为这是您要使用的事件(如果用户按住键,则每个插入的字符都会触发一次事件)

keyup 在字符插入输入后,当用户释放键时触发。 (如果用户保持按键按下,该事件只会触发一次)

【讨论】:

    猜你喜欢
    • 2017-02-21
    • 2017-02-04
    • 2013-10-19
    • 1970-01-01
    • 2020-10-09
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多