Introduction
AngularJS has many built-in directives that are used to specify the event. In this article we will discuss about keyboard event directives. AngularJS has the following directives to support keyboard event.
ngKeypress
This directive is useful to define custom behavior on keypress event. It executes at highest priority.
Syntax
<ANY ELEMENT ng-keypress="expression">
...
</ANY ELEMENT>
Example
HTML
- <h4>ngkeypress Example</h4>
- <div ng-controller="HomeController">
- <input ng-keypress="keyPress()">
- <br /> Key Press count: {{countKeyPress}}
- </div>
Controller - var app = angular.module("app", []);
- app.controller("HomeController", function($scope)
- {
- $scope.countKeyPress = 0;
- $scope.keyPress = function()
- {
- $scope.countKeyPress = $scope.countKeyPress + 1;
- }
- });
Output
ngKeyUp
This directive is useful to define custom behavior on key up event. It executes at highest priority.
Syntax
<ANY ELEMENT ng-keyup="expression">
...
</ANY ELEMENT>
Example
HTML
- <h4>ngkeyup Example</h4>
- <div ng-controller="HomeController">
- <input ng-keyup="keyUp()">
- <br /> Key up count: {{countKeyUp}}
- </div>
Controller
- var app = angular.module("app", []);
- app.controller("HomeController", function($scope)
- {
- $scope.countKeyUp = 0;
- $scope.keyUp = function()
- {
- $scope.countKeyUp = $scope.countKeyUp + 1;
- }
- });
Output ngKeyDown This directive is useful to define custom behavior on key down event. It executes at highest priority.
Syntax
<ANY ELEMENT ng-keydown="expression">
...
</ANY ELEMENT>
Example
HTML - <h4>ngkeydown Example</h4>
- <div ng-controller="HomeController">
- <input ng-keydown="keyDown()">
- <br /> Key down count: {{countKeyDown}}
- </div>
Controller: - var app = angular.module("app", []);
- app.controller("HomeController", function($scope)
- {
- $scope.countKeyDown = 0;
- $scope.keyDown = function()
- {
- $scope.countKeyDown = $scope.countKeyDown + 1;
- }
- });
Output Summary
This article is for helping us to learn various directives to support keyboard event.