Code


<!DOCTYPE html> <html> <head> <script src="angular.js"></script> <script src="script.js"></script> </head> <body ng-app="mainModule"> <div ng-controller="mainController"> <label>Type something: <input type="text" ng-keydown="onKeyDown($event)" ng-keyup="onKeyUp($event)" ng-keypress="onKeyPress($event)" /> </label><br /> <strong>KEY DOWN RESULT:</strong> {{onKeyDownResult}}<br /> <strong>KEY UP RESULT:</strong> {{onKeyUpResult}}<br /> <strong>KEY PRESS RESULT:</strong> {{onKeyPressResult}} </div> </body> </html>
angular.module("mainModule", []) .controller("mainController", function ($scope) { // Initialization $scope.onKeyDownResult = ""; $scope.onKeyUpResult = ""; $scope.onKeyPressResult = ""; // Utility functions var getKeyboardEventResult = function (keyEvent, keyEventDesc) { return keyEventDesc + " (keyCode: " + (window.event ? keyEvent.keyCode : keyEvent.which) + ")"; }; // Event handlers $scope.onKeyDown = function ($event) { $scope.onKeyDownResult = getKeyboardEventResult($event, "Key down"); }; $scope.onKeyUp = function ($event) { $scope.onKeyUpResult = getKeyboardEventResult($event, "Key up"); }; $scope.onKeyPress = function ($event) { $scope.onKeyPressResult = getKeyboardEventResult($event, "Key press"); }; });

Example


Description


Like with mouse events, AngularJS gives us a way to bind event handlers also for keyboard events with the ability to use Dependency Injection with the arguments of the handlers. Here are some directives useful for keyboard events:

  • ng-keydown
  • ng-keyup
  • ng-keypress

In the example we pass the $event variable to the event handlers to decode the key that was pressed. $event is just the same KeyboardEvent variable that we would have from the browser while working with plain JavaScript.