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.
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.
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.
Following is the example of getting key code of key pressed in keyboard using ng-keydown event in angularjs application.
<!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.
Following is the result of using ng-keydown event in angularjs applications.
This is how we can use ng-keydown event directive in angularjs applications to raise or call function while pressing key on keyboard.