AngularJS ng-keydown directive only working for <input> context?

Lukas N.P. Egger picture Lukas N.P. Egger · Mar 29, 2013 · Viewed 48.2k times · Source

I am pretty new to AngularJS but found it quite to my liking so far. For my current project I need hotkey functionality and was happy to see that it is supported since the 1.1.2 release.

The ng-keydown directive (http://code.angularjs.org/1.1.3/docs/api/ng.directive:ngKeydown) works as expected for input types but fails me for any other context like div etc. which seems odd given that the documentation says otherwise.

Here is an minimal example (http://jsfiddle.net/TdXWW/12/) of the working respectively the not working:

<input ng-keydown="keypress($event)">
<div ng-keydown="keypress($event)">

NOTE: I know this could be handled with plain jQuery (http://www.mkyong.com/jquery/how-to-check-if-an-enter-key-is-pressed-with-jquery/) but I much prefer to understand how to deal with it in AngularJS.

Answer

Jo&#227;o Jos&#233;zinho picture João Josézinho · Aug 16, 2013

I was having the same problem and was able to fix it by following this simple tip provided in this comment: https://stackoverflow.com/a/1718035/80264

You need to give the div a tabindex so it can receive focus.

<div id="testdiv" tabindex="0"></div>