在AngularJS绑定键盘事件 [英] Binding keyboard events in AngularJS

查看:1368
本文介绍了在AngularJS绑定键盘事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是绑定键盘键preSS活动的理想方式,如果你使用AngularJS?

现在,我设置的映射控制器内的键盘事件...

Right now I'm setting the mapping the keyboard events inside of a controller...

ngApp.controller('MainController', function MainController($scope) {
$scope.keyEvents = function() {
    if($('calculator').hasClass('open')) {
      switch(e.keyCode) {
       case 8:
          calc.deleteDigit();
          return;
        case 13:
          calc.equals();
            *etc., etc.*
      }
    }
    var $article = $("article");
    var $articleScrollTop = $article.scrollTop();
    //PageDown
    if(e.keyCode == 34) {
        $('article').animate({
            scrollTop: ($articleScrollTop + 480 + i++)
        }, 500);
    }
    //PageUp
    if(e.keyCode == 33) {
        $article.animate({
            scrollTop: ($articleScrollTop - 480 - i++)
        }, 500);
    }  
  }
}

我开始认为有一个最好的做法,当涉及到附加一个AngularJS应用程序内部键盘事件。

I'm beginning to think that there is a best practice when it comes to attaching keyboard events inside of an AngularJS app.

我应该使用 element.bind ,并设立相应的指令里面的键盘事件呢?

Should I be using element.bind and setting up the keyboard events inside of the corresponding directives instead?

在此先感谢您的帮助!

推荐答案

如果你想捕获这些事件?它是在全球范围内,或只是一些具体的事情?

Where are you trying to capture these events? Is it on a global scale or just something specific?

下面是限制性的输入字段日期密钥的一个例子。

Here's an example of limiting an input field for date keys.

然后你只装饰你的输入标记像

Then you just decorate your input tag like

HTML

<input type="text" date-keys />

角指令

angularDirectivesApp.directive('dateKeys', function () {
return {
    restrict: 'A',
    link: function (scope, element, attrs, controller) {
        debugger;
        element.on('keydown', function (event) {
            if (isNumericKeyCode(event.keyCode) || isForwardSlashKeyCode(event.keyCode) || isNavigationKeycode(event.keyCode))
                return true;
            return false;

        });
    }
}

function isNumericKeyCode(keyCode) {
    return (event.keyCode >= 48 && event.keyCode <= 57)
        || (event.keyCode >= 96 && event.keyCode <= 105);
}

function isForwardSlashKeyCode(keyCode) {
    return event.keyCode === 191;
}

function isNavigationKeycode(keyCode) {
    switch (keyCode) {
        case 8: //backspace
        case 35: //end
        case 36: //home
        case 37: //left
        case 38: //up
        case 39: //right
        case 40: //down
        case 45: //ins
        case 46: //del
            return true;
        default:
            return false;
    }
}
});

这篇关于在AngularJS绑定键盘事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆