Last active
August 29, 2015 14:19
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
}); | |
}; | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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