user2406718 user2406718 - 4 months ago 16x
AngularJS Question

How to unbind an keyboard short cut events in angular js

I created an angular directive that binds the keyboard short cut. However, once this is bind, it keeps the binding for all other divs. But i have attached only to one div. How do i unbind it after it executes and re bind when the user clicks within that div.

function ($document, $rootScope) {
return {
restrict: 'A',
link: function () {
$document.bind('keydown', function (e) {
if ((e.which == '115' || e.which == '83' ) && (e.ctrlKey || e.metaKey)){
} });

in controller

$rootScope.$on('Ctrl+s', function (e) {
$scope.$apply(function () {

in html

<div keypress-events>this is a div that binds keyboard shortcut</div>
<div>Another div which doesn't need a short cut key</div>

Appreciate any suggestions.


Don't use $document. The link function gets a scope and the element it's applied to passed to it.

link: function(scope, iElem){

When you bind to the document it is listening to events that bubble out the document (page). If you just bind to the element itself you'll only get the event handler triggered when that element has focus and the event occurs.