Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Catch global keypress

There are so many answers for this question but i can't figure it out how to solve two problems. After research i build very simple directive.

.directive('keypressEvents', function ($document) {
    return {
        restrict: 'A',
        link: function () {
            $document.bind('keypress', function (e) {
                alert(e.keyCode);
            });
        }
    }
});

First problem is more like a question, if i made it angular.service('myService', myServiceFunction);, will it work globally? Second is some key are not working, like ESC, arrows ctrl etc. I am working on this CODEPEN

like image 648
Honchar Denys Avatar asked Sep 10 '15 13:09

Honchar Denys


1 Answers

If it is really global handler you can bind it to the $document. You can add that in the run phase. There you will be able to inject other dependencies that you will need to implement the logic for handling. You can add it also in some service or directive if you think that there belongs more, you don't need to care where because just by binding it to the $document will make it global.

Otherwise you can create a directive like yours and bind it to the element. That gives you the option to choose on which element you will add the directive and if it's global then it's enough to add it on the body if not then you can choose your container element.

About the second question the event on Esc key is not triggered because Esc is key not a character. So instead of keypress you need to use keydown or keyup events.

Here is a working example of your code with keyup event.

$document.bind('keyup', function (e) {
    alert(e.keyCode);
});

I hope that this answer will help you.

like image 53
S.Klechkovski Avatar answered Sep 29 '22 14:09

S.Klechkovski