AngularJS > Events

ng-key events in AngularJS

How to perform key operations in AngularJS?


Like mouse related directives, there are few key related directives also in AngularJS and they are below

  1. ng-keydown - executes when key is starting to press  (this executes first and then keypress event executes)
  2. ng-keypress - executes when key is pressed
  3. ng-keyup - executes when key is left after pressing

In the <script> block, we have defined 3 functions for ng-keydown, ng-keypress and ng-keyup directives. Each function sets respective $scope property with the event name and current time.


<script>

    var app = angular.module("app", []);
    app.controller("KeyController", function ($scope) {
        $scope.KeyDown = function () {
            $scope.keydown = " Key down executes " + new Date().getTime();
        }

        $scope.KeyPress = function () {
            $scope.keypress = " Key press executes " + new Date().getTime();
        }

        $scope.KeyUp = function () {
            $scope.keyup = " Key up executes " + new Date().getTime();
        }
    });

</script>
<h2>Key Events</h2>
<div ng-app="app" ng-controller="KeyController">
    <p>Try writing something in the textbox below</p>    

    <input type="text" ng-keydown="KeyDown()" ng-keypress="KeyPress()" ng-keyup="KeyUp()" />

    <hr />
    <p>Key down - {{ keydown }}</p>
    <p>Key press - {{ keypress }}</p>
    <p>Key up - {{ keyup }}</p>

</div>

In the HTML block, we have decored a text box with ng-keydown, ng-keypress and ng-keyup directive that calls KeyDown(), KeyPress() and KeyUp() function respectively.

When user starts writing something in the text box, respecive event executes and writes the message below in the paragraph.

Output

key events in angularjs

 Views: 19809 | Post Order: 40




Write for us






Hosting Recommendations