Skip to content

Instantly share code, notes, and snippets.

@schottra
Last active August 29, 2015 14:19
Show Gist options
  • Save schottra/65991c3c4fd44f41f5e7 to your computer and use it in GitHub Desktop.
Save schottra/65991c3c4fd44f41f5e7 to your computer and use it in GitHub Desktop.
A reusable escape handler mixin that will call a function of your choice when escape is pressed and automatically detach when the scope is destroyed
angular.module('myModule').factory('escapeHandler', function($document){
var ESCAPE_KEY = 27;
return function(scope, handler){
var eventHandler = function(keyEvent){
if(keyEvent.keyCode === ESCAPE_KEY){ // use `keyCode`, not `which`
scope.$apply(handler);
}
};
$document[0].addEventListener('keydown', eventHandler, true); // using capture mode
scope.$on('$destroy', function(){
$document[0].removeEventListener('keydown', eventHandler, true); // third argument must match the `addEventListener` call
});
};
});
angular.module('myModule').directive('someDirective', function(escapeHandler){
return {
link: function(scope){
scope.done = function(){
//whatever your close logic is
};
escapeHandler(scope, scope.done);
// or you can do an inline function
escapeHandler(scope, function(){
scope.hideTheDialog = true;
});
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment