AngularJS ngKeypress Directive



  • ng-keypress directive is used to specify the custom behavior that execute when the keyboard is used on the specific HTML element.
  • In AngularJS, the ng-keypress directive will not override the HTML element’s original onkeypress event, both will be executed.
  • The ng-keypress directive is executing at the priority level “0”.
  • ng-keypress is supported by <input>, <select>, <textarea>, and other 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-keypress directive in AngularJS:

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

Parameter value for ng-keypress directive in AngularJS:

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

Sample coding for ng-keypress 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-keypress Directive in AngularJS</h2>
        <input ng-keypress="count = count + 1" ng-init="count=0">
        <h3>The keypress count : {{ count }}</h3>
    </body>
</html>

Code Explanation for ng-keypress directive in AngularJS:

Code Explanation for AngularJS ngKeypress 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-keypress= “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-keypress directive in AngularJS:

Sample Output for AngularJS ngKeypress Directive

  1. The output displays the content “Welcome To Wikitechy” in the text box.
  2. The output shows that the content “The keydown count:20” 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 ngKeypress directive