Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to watch for a keypress combination in Angularjs? [duplicate]

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?

like image 216
Korra Avatar asked Nov 11 '13 16:11

Korra


1 Answers

Looks like you can use the ng-keydown to do this.

Here is a working plunker.

For this sample, I just bound ng-keydown to <body>. Works pretty well to catch all the keyboard events globally.

As @charlietfl points out, ng-keydown registers a lot of keyboard events so to make this usable would be a lot of work. For example, if you were trying to listen for a combination (like ctrl + r), then the ctrl key will register many times.

JS:

var myApp = angular.module('myApp', []);

myApp.controller('Ctrl', function($scope) {


    $scope.keyBuffer = [];

    function arrays_equal(a,b) { return !(a<b || b<a); }

    $scope.down = function(e) {

      $scope.keyBuffer.push(e.keyCode);

      var upUp = [38, 38, 40, 40, 37, 39, 37, 39, 66, 65];
      if (arrays_equal(upUp, $scope.keyBuffer)) {

        alert('thats it!');
      }
    };

  });

HTML:

<body ng-controller="Ctrl" ng-keydown="down($event)">
like image 153
Davin Tryon Avatar answered Sep 27 '22 17:09

Davin Tryon