What is AngularJS way to create global keyboard shortcuts?
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>'
};
}
]);
Use $document.bind
:
function FooCtrl($scope, $document) {
...
$document.bind("keypress", function(event) {
console.debug(event)
});
...
}
I can't vouch for it just yet but I've started taking a look at AngularHotkeys.js:
http://chieffancypants.github.io/angular-hotkeys/
Will update with more info once I've got my teeth into it.
Update 1: Oh there's a nuget package: angular-hotkeys
Update 2: actually very easy to use, just set up your binding either in your route or as I'm doing, in your controller:
hotkeys.add('n', 'Create a new Category', $scope.showCreateView);
hotkeys.add('e', 'Edit the selected Category', $scope.showEditView);
hotkeys.add('d', 'Delete the selected Category', $scope.remove);