How to use a keypress event in AngularJS? How to use a keypress event in AngularJS? angularjs angularjs

How to use a keypress event in AngularJS?


You need to add a directive, like this:

Javascript:

app.directive('myEnter', function () {    return function (scope, element, attrs) {        element.bind("keydown keypress", function (event) {            if(event.which === 13) {                scope.$apply(function (){                    scope.$eval(attrs.myEnter);                });                event.preventDefault();            }        });    };});

HTML:

<div ng-app="" ng-controller="MainCtrl">    <input type="text" my-enter="doSomething()">    </div>


An alternative is to use standard directive ng-keypress="myFunct($event)"

Then in your controller you can have:

...$scope.myFunct = function(keyEvent) {  if (keyEvent.which === 13)    alert('I am an alert');}...


My simplest approach using just angular build-in directive:

ng-keypress, ng-keydown or ng-keyup.

Usually, we want add keyboard support for something that already handled by ng-click.

for instance:

<a ng-click="action()">action</a>

Now, let's add keyboard support.

trigger by enter key:

<a ng-click="action()"    ng-keydown="$event.keyCode === 13 && action()">action</a>

by space key:

<a ng-click="action()"    ng-keydown="$event.keyCode === 32 && action()">action</a>

by space or enter key:

<a ng-click="action()"    ng-keydown="($event.keyCode === 13 || $event.keyCode === 32) && action()">action</a>

if you are in modern browser

<a ng-click="action()"    ng-keydown="[13, 32].includes($event.keyCode) && action()">action</a>

More about keyCode:
keyCode is deprecated but well supported API, you could use $evevt.key in supported browser instead.
See more in https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key