AngularJS - 同时多键preSS [英] AngularJS - Multiple keypress at the same time

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

问题描述

我有如下的 $广播抓关键presses在角:

I have the following $broadcast to catch keypresses in Angular:

$document.bind('keypress', function(event) {
    var key = event.which;
    $rootScope.$broadcast('keypress', event);
    $rootScope.$broadcast('keypress:' + key, event);
});

和我与 $监听

不过,我想,当两个键同时pssed $ P $来检测,说输入取值是$ p $同时pssed(未组合一一后跟另一个)。

However, I want to detect when two keys are pressed at the same time, say enter and s are pressed at the same time (not a combination one one followed by another).

什么是这样做的最佳方式?

What is the best way of doing this?

修改

我想是有:

var keys = [];
$document.bind('keydown', function(event) {
    keys[event.which] = true;
});
$document.bind('keyup', function(event) {
    delete keys[event.which];
});

$document.bind('keypress', function(event) {
    var key = event.which;
    var keysPressed = [];
    angular.forEach(keys, function(value, key) {
        keysPressed += 'keypress:' + key;
    });
    $rootScope.$broadcast('keypress', event);
    $rootScope.$broadcast(keysPressed, event);
});

所以,如果我有多个键presses,然后创建正确的 $播出。然而问题,成为现在的顺序问题(即,如果我preSS A 然后输入,那么 $广播键preSS:58key preSS:13 如果我preSS的其他方式,我得到键preSS:13key preSS:58

So if I have multiple keypresses, then I create the correct $broadcast. The problem, however, becomes that the order matters now (i.e., if I press a then enter, then the $broadcast is keypress:58keypress:13 and if I press the other way, I get keypress:13keypress:58)

推荐答案

Boradcast使用办法不多在我看来。相反,也许把它作为一个指令?这是用户$ P $的一个例子pssing下来Shift + Tab键,并触发一个事件,像这样:

Boradcast is used way to much in my opinion. Instead, maybe use it as a directive? This is an example of user pressing down Shift+Tab and it fires an event like so:

<input ng-shift-tab="prevStep('email')" />

app.directive('ngShiftTab', function() {
return function(scope, element, attrs) {
    var map = {9: false, 16: false};

    element.bind("keydown", function(event) {
        if (event.which in map) {
            map[event.which] = true;
            if (map[9] && map[16]) {
                scope.$apply(function(){
                    scope.$eval(attrs.ngShiftTab, {'event': event});
                });
                event.preventDefault();
            }
        }
    });
    element.bind("keyup", function(event) {
        if (event.which in map) {
            map[event.keyCode] = false;
        }
    });
};
})

这篇关于AngularJS - 同时多键preSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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