Keyboard Event Directives In AngularJS

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

  1. <h4>ngkeypress Example</h4>  
  2.     <div ng-controller="HomeController">  
  3.     <input ng-keypress="keyPress()">  
  4.     <br /> Key Press count: {{countKeyPress}}   
  5. </div>  
Controller
  1. var app = angular.module("app", []);  
  2. app.controller("HomeController", function($scope)  
  3. {  
  4.     $scope.countKeyPress = 0;  
  5.     $scope.keyPress = function()  
  6.     {  
  7.         $scope.countKeyPress = $scope.countKeyPress + 1;  
  8.     }  
  9. });  
Output

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
  1. <h4>ngkeyup Example</h4>  
  2. <div ng-controller="HomeController">  
  3.     <input ng-keyup="keyUp()">  
  4.     <br /> Key up count: {{countKeyUp}}   
  5. </div>  
Controller
  1. var app = angular.module("app", []);  
  2. app.controller("HomeController", function($scope)  
  3. {  
  4.     $scope.countKeyUp = 0;  
  5.     $scope.keyUp = function()  
  6.     {  
  7.         $scope.countKeyUp = $scope.countKeyUp + 1;  
  8.     }  
  9. });  
Output

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
  1. <h4>ngkeydown Example</h4>  
  2. <div ng-controller="HomeController">  
  3.     <input ng-keydown="keyDown()">  
  4.     <br /> Key down count: {{countKeyDown}}   
  5. </div>  
Controller:
  1. var app = angular.module("app", []);  
  2. app.controller("HomeController", function($scope)  
  3. {  
  4.     $scope.countKeyDown = 0;  
  5.     $scope.keyDown = function()  
  6.     {  
  7.         $scope.countKeyDown = $scope.countKeyDown + 1;  
  8.     }  
  9. });  
Output

output

Summary

This article is for helping us to learn various directives to support keyboard event.