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

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>