How to trigger a method with the keyboard shortcut in AngularJS

ava-s-alexey-zvegintcev

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:

.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;
                }
            });
        };
    });Code language: PHP (php)

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

ava-s-alexey-zvegintcev
Lead JavaScript Developer