AngularJS ngKeydown Directive



  • ng-keydown directive is used to specify the custom behavior that execute when the keyboard is used on the specific HTML element.
  • In AngularJS, the ng-keydown directive will not override the HTML element’s original onkeydown event, both will be executed.
  • The ng-keydown directive is executing at the priority level “0”.
  • ng-keydown is supported by <input>, <select>, <textarea>, and others editable HTML element.

Difference between keypress and keydown:

Keydown:

  • Fires when the user depresses a key.
  • It repeats while the user keeps the key depressed.

Keypress:

  • Fires when an actual character is being inserted in, for example, a text input.
  • It repeats while the user keeps the key depressed.

Syntax for ng-keydown directive in AngularJS

<element ng-keydown= “expression” ></element>

Parameter value for ng-keydown directive in AngularJS:

Value Description
expression It is used to define an expression that execute when a key is pressed.

Sample coding for ng-keydown directive in AngularJS:

 Tryit<!DOCTYPE html>
<html>
    <head>
        <title>Wikitechy AngularJS Tutorials</title>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/
                    angular.min.js"> </script>
    </head>
    <body ng-app="">
        <h2>Wikitechy ng-keydown Directive in AngularJS</h2>
        <input ng-keydown="count = count + 1" ng-init="count=0">
        <h3>The keydown count : {{ count }} </h3>
    </body>
</html>

Code Explanation for ng-keydown directive in AngularJS:

Code Explanation for AngularJS ngKeydown Directive

  1. AngularJS is distributed as a JavaScript file, and can be added to a HTML page with a <script> tag.
  2. The AngularJS application is defined by ng-app=" ". The application runs inside the <body> tag. It’s also used to define a <body> tag as a root element.
  3. The ng-keydown= “count=count+1” is used to increase the count variable by one, every time the key is pressed in the input field.
  4. The ng-init="count = 0" is used to define the initial value of the count variable is “0”.
  5. The {{ count }} is used to dynamically bind the count variable value when the user press the key in the input field.

Sample Output for ng-keydown directive in AngularJS:

Sample Output for AngularJS ngKeydown Directive

  1. The output displays the content “Welcome To Wikitechy” in the text box.
  2. The output shows that the content “The keydown count:23” when the user typed the “Welcome To Wikitechy” in the text box. Here the variable “count” will increase the value by 1, every time a key is pressed in the text box.

Related Searches to angularjs ngKeydown directive