Using key press event in Angular JS

Yasser Shaikh
Nov 24, 2015 · 1 min read

It is a very common use case to catch event of certain key press, like the enter key for example. In this post, I am gonna write about how to handle key press event in Angular JS — using the so called “angular way” approach.

Problem statement:
Let’s define a problem statement to begin with. I have a form with one text field and a button next to it.

enter image description here
enter image description here

And then there was a directive…
This directive checks for keydown & keypress and checks the keycode, 13 in case of the enter key.

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

and that’s about it. We are done.

Usage:

<div ng-app="" ng-controller="WierdController">
<input type="text" enter-pressed="doSomething()">
<button ng-click="doSomething()">Let's go!</button>
</div>

Yasser Shaikh's blog

It's supposed to be automatic, but actually you have to push this button.

Yasser Shaikh

Written by

Yasser Shaikh's blog

It's supposed to be automatic, but actually you have to push this button.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade