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 ) {
                e.preventDefault();

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

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

HTML

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>
        </span>
    </div>
</div>

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

Summary

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!

Meet the Author

Kevin Leary, Boston WordPress Developer of 10 Years

I'm a freelance web developer and WordPress consultant in Boston, MA with 13 years of experience building websites and applications. View a portfolio of my work or request an estimate for your next project.