Skip to content

Instantly share code, notes, and snippets.

@rafinskipg
Created June 10, 2015 13:21
Show Gist options
  • Save rafinskipg/9d44284a5f9e77c6d2b1 to your computer and use it in GitHub Desktop.
Save rafinskipg/9d44284a5f9e77c6d2b1 to your computer and use it in GitHub Desktop.
Angular JS Shortcut Directive
/** ... **/
$scope.save = function(){
}
$scope.delete = function(){
}
/** ... **/
'use strict';
/* global jQuery */
/**
* @ngdoc directivew
* @name directive:shortcut
* @description Directive for creating key shortcuts
* # shortcut
*/
angular.module('App')
.directive('shortcut', function() {
return {
name: 'shortcut',
restrict: 'A',
scope: true,
replace: true,
link: function($scope, $el, attrs) {
/*exported options */
var shortcuts;
try {
shortcuts = JSON.parse(attrs.shortcut.replace(/'/g, '"'));
} catch (e) {
throw new Error('Invalid JSON for shortcut');
}
var options = [];
Object.keys(shortcuts).forEach(function(key) {
var keys = key.split('+');
var shiftIndex = keys.indexOf('shift');
var useShift = shiftIndex !== -1;
if (useShift) {
keys.splice(shiftIndex, 1);
}
var ctrlIndex = keys.indexOf('ctrl');
var useCtrl = ctrlIndex !== -1;
if (useCtrl) {
keys.splice(ctrlIndex, 1);
}
var altIndex = keys.indexOf('alt');
var useAlt = altIndex !== -1;
if (useAlt) {
keys.splice(altIndex, 1);
}
var opts = typeof(shortcuts[key]) === 'string' ? {
callback: shortcuts[key],
preventDefault: false
} : shortcuts[key];
if (!opts.callback) {
throw new Error('Shortuct needs a callback');
}
options.push({
shiftKey: useShift,
ctrlKey: useCtrl,
altKey: useAlt,
keys: keys,
callback: opts.callback,
preventDefault: opts.preventDefault
});
});
var elSelector = attrs.el || document;
jQuery(elSelector).on('keypress', function(e) {
/* global options */
options.forEach(function(option) {
if (option.shiftKey && !e.shiftKey || option.altKey && !e.altKey || option.ctrlKey && !e.ctrlKey) {
return false;
}
var keyPressed = option.keys.indexOf(String.fromCharCode(e.which)) !== -1;
if (keyPressed) {
console.log(option, e.shiftKey, e.altKey, e.ctrlKey, 'key pressed', String.fromCharCode(e.which));
$scope.$apply($scope[option.callback]);
if (option.preventDefault) {
e.preventDefault();
return false;
}
}
});
});
}
};
});
<div shortcut="{'shift+S' : 'save', 'shift+W' : 'delete'}"></div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment