Reputation: 28076
I am currently using a directive to implement keyboard shortcuts in my angular app. The directive called "keyCapture". It is included in the body tag of my index page.
<body ng-controller="MainCtrl" key-capture>
This directive uses a mix of $broadcast and other methods to get things done.
angular.module('plunker').directive('keyCapture',['$state','$rootScope',function($state, $rootScope){
var shortCutKeys = [];
return {
link: function(scope,element,attrs,controller){
element.on('keydown',function(e){
shortCutKeys.push(e.keyCode);
if (shortCutKeys.length === 2){
var key2 = shortCutKeys.pop();
var key1 = shortCutKeys.pop();
/*press g and 1 - navigate to a different state*/
if (key1 === 71 && key2 == 49) {
$state.transitionTo('option1');
}
/*press g and 2 - navigate to a different state*/
if (key1 === 71 && key2 == 50) {
$state.transitionTo('option2');
}
/*press g and 3 - call a function */
if (key1 === 71 && key2 == 51) {
$rootScope.$broadcast('option1-event1')
}
/*press g and 4 - call a function*/
if (key1 === 71 && key2 == 52) {
$rootScope.$broadcast('option1-event2')
}
}
})
}
};
}]);
The plnkr is available here: http://plnkr.co/yqS3O3wGoiE00tPOzcLP
I am skeptical if this is the right way to implement keyboard shortcuts into a app. Anyone has a better idea of how to integrate keyboard shortcuts into a app.. kindly comment .. or event better.. explain with some code sample.
Thanks
Upvotes: 0
Views: 2840
Reputation: 35276
Have you checked out Angular Hotkeys ? Brad Green the project manager of Angular has mentioned how awesome it is a few times. Probably better than implementing yourself unless you're just trying to learn.
Upvotes: 1