How to watch for a keypress combination in Angular

2019-03-15 19:50发布

This question already has an answer here:

I'm trying to get my controller to watch for a combination of keys. For argument's sake, let's say: up up down down left right left right b a. How can I get angular to look out for these regardless of where in the page the user currently is?

7条回答
Bombasti
2楼-- · 2019-03-15 20:43

This is all untested, but you could use ng-keypress

<body ng-keypress="logKeys($rootScope,$event)">...</body>

To call a function something like:

appCtrl.$scope.logKeys = function($rootScope,$event){
    $rootScope.keyLog.shift(); // Remove First Item of Array
    $rootScope.keyLog.push($event.keyCode); // Adds new key press to end of Array
    if($scope.$rootScope.keyLog[0] !== 38) { return false; } // 38 == up key
    if($scope.$rootScope.keyLog[1] !== 38) { return false; }
    if($scope.$rootScope.keyLog[2] !== 40) { return false; } // 40 = down key
    if($scope.$rootScope.keyLog[3] !== 40) { return false; }
    if($scope.$rootScope.keyLog[4] !== 27) { return false; } // 37 = left key
    if($scope.$rootScope.keyLog[5] !== 39) { return false; } // 39 = right key
    if($scope.$rootScope.keyLog[6] !== 37) { return false; }
    if($scope.$rootScope.keyLog[7] !== 39) { return false; }
    if($scope.$rootScope.keyLog[8] !== 65) { return false; } // 65 = a
    if($scope.$rootScope.keyLog[9] !== 66) { return false; } // 66 = b

    $rootScope.doThisWhenAllKeysPressed(); // Got this far, must all match!
    return true;
}

Outside an input field, I don't think ng-keypress works, but the keypress from angular-ui might.

I'm sure there should be an array diff kinda function too, but the specific call evades me right now.

查看更多
登录 后发表回答