'How to trigger a method with the keyboard shortcut in AngularJS' post illustration

How to trigger a method with the keyboard shortcut in AngularJS

avatar

If you are, for example, working on a chat application, one of the features that the user expects is an ability to send a message with a keyboard shortcut. The example of a directive below shows how this can be achieved for Shift + Enter combination:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
.directive('sendMessage', function(){
        return function (scope, element) {
            var shiftDown = false;
            element.bind("keydown", function (event) {

                // sets shiftDown to true if the shift key (key code is 16) is pressed
                if(event.which === 16) {
                    shiftDown = true;
                }

                // sends the message if "enter" is pressed and "shift" is being held down
                if(event.which === 13 && shiftDown) {
                    event.preventDefault();
                    scope.send();
                    scope.$apply();
                }
            });

            // sets shiftDown to false if the shift key has been released
            element.bind("keyup", function (event) {
                if(event.which === 16) {
                    shiftDown = false;
                }
            });
        };
    });

You can play with a simple chat app that uses this directive on CodePen, and fork the app on GitHub.

If you're looking for a developer or considering starting a new project,
we are always ready to help!