AngularJS ng-keydown Event with Example

Here we will learn what is ng-keydown event in angularjs, use of ng-keydown in angularjs, how to get key code of key pressed on keyboard using ng-keydown directive in angularjs with example.

AngularJS ng-keydown Event Directive

In angularjs ng-keydown event directive is used to define events or execute custom behaviour functions immediately on key press in keyboard. 

 

The ng-keydown event will raise immediately whenever we press key on keyboard before release itself.

 

Suppose in angularjs if you want to raise an event on key press or call some custom functions immediately on key press it’s better to use ng-keydown event.

Syntax of AngularJS ng-keydown Event

Following is the syntax of using angularjs ng-keydown event directives in applications.

 

<element ng-keydown="expression">

--Your Code--

</element>

The ng-keydown event in angularjs will execute expression whenever key is pressed and it will support <input>, <select>, <textarea> elements.

 

The angularjs ng-keydown event will not override onkeydown event of html elements both will execute separately.

Example of AngularJS ng-keydown Event

Following is the example of getting key code of key pressed in keyboard using ng-keydown event in angularjs application.

 

Live Preview

<!DOCTYPE html>

<html>

<head>

<title>

AngularJs ng-keydown Event with Example

</title>

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<script type="text/javascript">

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

app.controller('ngkeydownCtrl', function ($scope) {

$scope.getkeys = function (event) {

$scope.keyval = event.keyCode;

}

});

</script>

</head>

<body>

<div ng-app="ngkeydownApp" ng-controller="ngkeydownCtrl">

<h2>AngularJS ng-keydown Event Example</h2>

Enter Text: <input type="text" ng-keydown="getkeys($event)" ng-model="ftxt"><br /><br />

<span style="color:Red">Last Key Code: {{keyval}}</span>

</div>

</body>

</html>

If you observe above angularjs ng-keydown example we are calling function getkeys() with $event object as parameter and showing key code of key pressed in keyboard.

Output of AngularJS ng-keydown Event Example

Following is the result of using ng-keydown event in angularjs applications.

 

Angularjs ng-keydown event example result or output

 

This is how we can use ng-keydown event directive in angularjs applications to raise or call function while pressing key on keyboard.