AngularJS ng-keypress Directive
Last Updated :
11 Jul, 2025
Improve
The ng-keypress Directive in AngluarJS is used to apply custom behavior on a keypress event. It is mainly used to specify what to do when the keyboard is utilized with a particular HTML element. The order of sequence that the key is pressed is Keydown, Keypress, and keyup. It is supported by <input>, <select> and <textarea> element.
Syntax:
<element ng-keypress="expression"> Contents... </element>
Parameter value:
- expression: It tells what to do when the key is pressed.
Example 1: This example uses the ng-keypress Directive in AngularJS to display key values.
<!DOCTYPE html>
<html>
<head>
<title>ng-keypress Directive</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
<script type="text/javascript">
var app = angular.module("app", []);
app.controller("geek", function ($scope) {
$scope.getkeys = function (event) {
$scope.keyval = event.keyCode;
};
});
</script>
</head>
<body style="text-align: center">
<div ng-app="app" ng-controller="geek">
<h1 style="color: green">
GeeksforGeeks
</h1>
<h3>ng-keypress Directive</h3>
Enter Text: <input type="text"
ng-keypress="getkeys($event)" />
<br /><br />
<span style="color: Red">
Key Code: {{keyval}}
</span>
</div>
</body>
</html>
Output:

Example 2: This example describes the use of the ng-keypress Directive in AngularJS where it displays the total number of counts the key is pressed simultaneously.
<!DOCTYPE html>
<html>
<head>
<title>ng-keypress Directive</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
<style>
body {
text-align: center;
font-family: sans-serif;
}
h1 {
color: green;
}
</style>
</head>
<body ng-app="">
<h1>GeeksforGeeks</h1>
<h2>ng-keypress Directive</h2>
<textarea ng-keypress="add = add + 1"
ng-init="add=0" >
</textarea>
<p> {{add}} times key is pressed.</p>
</body>
</html>
Output:

Reference: https://docs.angularjs.org/api/ng/directive/ngKeypress