Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 619
Lukas N.P. Egger Avatar asked Mar 29 '13 13:03

Lukas N.P. Egger


People also ask

How do I use NG Keydown?

The ng-keydown directive tells AngularJS what to do when the keyboard is used on the specific HTML element. The ng-keydown directive from AngularJS will not override the element's original onkeydown event, both will be executed.

Which directive do we use to inform AngularJS about the parts controlled by it?

The ngRef attribute tells AngularJS to assign the controller of a component (or a directive) to the given property in the current scope. It is also possible to add the jqlite-wrapped DOM element to the scope. The ngRepeat directive instantiates a template once per item from a collection.

What is ngchange?

The ng-change event is triggered at every change in the value. It will not wait until all changes are made, or when the input field loses focus. The ng-change event is only triggered if there is a actual change in the input value, and not if the change was made from a JavaScript.

Which directive defines the root element in AngularJS?

The ng-app directive defines the root element of an AngularJS application and starts an AngularJS Application. The ng-app directive will auto-bootstrap (automatically initialize) the application when a web page is loaded. It is also used to load various AngularJS modules in AngularJS Application.


2 Answers

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> 
like image 127
João Josézinho Avatar answered Sep 21 '22 16:09

João Josézinho


Thanks! To wrap this up I got this working by, injecting $document into my directive, then:

MyApp.directive('myDirective', function($document) { return { ...  $document.keydown(function(e){    console.log(e)  }) } 
like image 37
Finn Johnsen Avatar answered Sep 19 '22 16:09

Finn Johnsen