I’ve been doing a lot work with Angular.js lately, and I continue to find directives more and more useful. Here’s a common directive I frequently use to trigger a scope method when the ENTER key is pressed.

Directive JS

// Enter key press
mainApp.directive( [ 'onEnterKey', function onEnterKeyDirective() {
    return function ( scope, element, attrs ) {
        element.bind( "keydown keypress", function ( e ) {
            if ( e.which === 13 ) {

                scope.$apply( function () {
                    scope.$eval( attrs.onEnterKey );
                } );
        } );
} ] );

In this case mainApp represents a top level application module (var mainApp = angular.module( "mainApp", [] );.


Once this has been added to your Angular app you can use the on-enter-key="..." attribute on any HTML element within a controller scope. For example:

<div class="form-group">
    <div class="input-group input-group--search">
        <input type="text" class="form-control form-control-sm" ng-model="query.search" on-enter-key="queryReports()" placeholder="Search reports...">
        <span class="input-group-btn">
            <button class="btn btn-success btn-sm" type="button" ng-click="queryReports()">Find <i class="ion-ios-search-strong"></i></button>

Here I’m using the triggering the method, queryReports(), when a user presses the ENTER key or clicks the “Find” button.


This should provide a simple and easy way to handle an ENTER keypress event within an Angular.js controller scope context. Drop any questions you have in the comments below and I’ll do my best to help answer any questions!

About the Author

Kevin Leary is a freelance web developer in Boston, MA specializing in enterprise WordPress development, conversion optimization and JavaScript development.