Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is AngularJS way to create global keyboard shortcuts?

I suppose that I should use directive, but it seems strange to add directive to body, but listen events on document.

What is a proper way to do this?

UPDATE: Found AngularJS UI and saw their realization of keypress directive.

like image 580
ValeriiVasin Avatar asked Feb 23 '13 19:02

ValeriiVasin


People also ask

What is the keyboard shortcut for global search?

Open the Global Search app by pressing its shortcut (the default is SUPER + / - Windows key + forward slash).

What are global shortcuts?

A global hotkey is a combination of keyboard buttons that execute a command in any application or window, like launching your calculator app for example. It doesn't matter if you're in Word, Excel, in a browser, or on the desktop.


1 Answers

I would say a more proper way (or "Angular way") would be to add it to a directive. Here's a simple one to get you going (just add keypress-events attribute to <body>):

angular.module('myDirectives', []).directive('keypressEvents', [   '$document',   '$rootScope',   function($document, $rootScope) {     return {       restrict: 'A',       link: function() {         $document.bind('keypress', function(e) {           console.log('Got keypress:', e.which);           $rootScope.$broadcast('keypress', e);           $rootScope.$broadcast('keypress:' + e.which, e);         });       }     };   } ]); 

In your directive you can then simply do something like this:

module.directive('myDirective', [   function() {     return {       restrict: 'E',       link: function(scope, el, attrs) {         scope.keyPressed = 'no press :(';         // For listening to a keypress event with a specific code         scope.$on('keypress:13', function(onEvent, keypressEvent) {           scope.keyPressed = 'Enter';         });         // For listening to all keypress events         scope.$on('keypress', function(onEvent, keypressEvent) {           if (keypress.which === 120) {             scope.keyPressed = 'x';           }           else {             scope.keyPressed = 'Keycode: ' + keypressEvent.which;           }         });       },       template: '<h1>{{keyPressed}}</h1>'     };   } ]); 
like image 114
jmagnusson Avatar answered Sep 16 '22 19:09

jmagnusson