Angular Directive Escape Key Function

Here is a quick angular directive escape key function on a div that I found somewhere (if you know the source let me know so I can give credit. It is quite a simple directive that allows you to apply it to a div or any element and assign a function for it to call.

The Directive:

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

                event.preventDefault();
            }
        });
    };
});

Now applying the directive to an element looks like this:

//Note the tabindex="0" gives the div focus.
<div ng-esc="closeLightBoxWithEsc()" tabindex="0"></div>

Finally, the function we are calling:

$scope.closeLightBoxWithEsc = function(){
    //Anything your heart desires.
};

Leave a Reply

Your email address will not be published. Required fields are marked *

StackOverflow Profile