简体   繁体   English

如何在Angular JS中取消键盘快捷键事件的绑定

[英]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. 但是,一旦绑定,它将为所有其他div保留绑定。 But i have attached only to one div. 但我只重视一个div。 How do i unbind it after it executes and re bind when the user clicks within that div. 当它执行后,我如何解除绑定并在用户单击该div时重新绑定。 ex: 例如:

angular.module('Dummy').directive('keypressEvents',
function ($document, $rootScope) {
  return {
    restrict: 'A',
    link: function () {
    $document.bind('keydown', function (e) {
      if ((e.which == '115' || e.which == '83' ) && (e.ctrlKey || e.metaKey)){
        $rootScope.$broadcast('Ctrl+s');
      }
    });
  }
}  });

in controller 在控制器中

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

in html 在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. 不要使用$ document。 The link function gets a scope and the element it's applied to passed to it. 链接函数获取作用域和应用于该作用域的元素。

link: function(scope, iElem){
  iElem.bind(...
}

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. 如果仅绑定到元素本身,则只有在该元素获得焦点并且事件发生时,才会触发事件处理程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM