Can I use an AngularJs keypress inside a div and not an input?


Good morning,

I'm starting to make a game that is a 100x100 board on the screen, I want to be able to recognize when the keyboard dates are pressed so that the player moves along the board, I'm using AngularJS, for that there is the ng directive -keypress, but it seems that only works within an input, does anyone have another idea?

My main idea was:

<div ng-keypress = press($event)> </div>

Another idea would be in the body, but I'm not sure, it would be something like this:

<body ng-keypress = press($event)> </body>
asked by Carlos Aguilera 17.04.2017 в 18:28

2 answers


If it is possible to know which key was pressed without needing to be in input Here is an example of how to do it:

window.onkeydown = keypress

function keypress(){
 if (event.keyCode>=37 && event.keyCode<=40)
  console.log("pulso la tecla " + event.key)
presiona las flechas de direccionamiento

The line window.onkeydown corresponds to the method of the window object to trigger an event at the moment of pressing a key, said event in principle does not execute any action but if we associate it with the function = keypress , will execute this function and that is why when you press a key, the function keypress is displayed. in console a message corresponding to one of the addressing arrows.

answered by 17.04.2017 / 19:36

I found the answer to your question in Stack overflow in English, I leave the link: link

If battles for English, basically says that there are several methods that you can use as ng-keypress or ng-keyup etc, and that it does not matter which html tag you put them as long as you respect certain restrictions for Internet Explorer.

Check out this documentation: ngKeypress

answered by 17.04.2017 в 20:19