Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can AngularJS ng-Keyup pass in which key was pressed?

The documentation for Angular's ngkeyup is virtually non-existant. I have a container div for my view that I want to apply key events to, but I want to control them from a function in my controller.

I'm trying to do something like this:

view:

<div class="container" ng-keyup="keyPress(e)"></div> 

Controller:

$scope.keyPress = function(e){    console.log(e); // where 'e' is the keycode of whatever was pressed } 

Is this possible at all? I can't find any information, anywhere, on what ng-keyup actually does and how to use it! For instance, I want to trigger an event when the left arrow key (37) is pressed, how would I achieve this with Angular?

like image 756
JVG Avatar asked Oct 25 '13 07:10

JVG


People also ask

How to use ng-keyup in AngularJS?

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

What is the use of Keyup in angular?

(keyup) is an Angular event binding to respond to any DOM event. It is a synchronous event that is triggered as the user is interacting with the text-based input controls. When a user presses and releases a key, the (keyup) event occurs.

How does angular handle keypress events?

you can easily use keypress event in angular 6, angular 7, angular 8, angular 9, angular 10, angular 11, angular 12, angular 13 and angular 14 application. When user will press key on input box field then trigger onKeypressEvent() of angular component. we will use (change) attribute for call function.

What is Ng change in angular?

AngularJS ng-change DirectiveThe 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.


2 Answers

You can do something like, passing $event object.

<div class="container" ng-keypress="keyPress($event)"></div>

This is mentioned in documentation

Expression to evaluate upon keyup. (Event object is available as $event and can be interrogated for keyCode, altKey, etc.)

like image 77
Chandermani Avatar answered Oct 09 '22 12:10

Chandermani


Template:

<div class="container" ng-keyup="keyPress($event.keyCode)"></div> 

Controller:

$scope.keyPress = function(keyCode){    console.log(keyCode);  } 
like image 39
franc Avatar answered Oct 09 '22 14:10

franc