什么是AngularJS创建全局键盘快捷键的方法?

Val*_*sin 77 javascript angularjs

我想我应该使用指令,但是向body添加指令似乎很奇怪,但是在文档上监听事件.

这样做的正确方法是什么?

更新:找到AngularJS UI并看到他们实现的keypress指令.

jma*_*son 69

我会说更合适的方式(或"Angular方式")将其添加到指令中.这是一个简单的让你前进(只需添加keypress-events属性<body>):

angular.module('myDirectives', []).directive('keypressEvents', [
  '$document',
  '$rootScope',
  function($document, $rootScope) {
    return {
      restrict: 'A',
      link: function() {
        $document.bind('keypress', function(e) {
          console.log('Got keypress:', e.which);
          $rootScope.$broadcast('keypress', e);
          $rootScope.$broadcast('keypress:' + e.which, e);
        });
      }
    };
  }
]);
Run Code Online (Sandbox Code Playgroud)

在你的指令中,你可以简单地做这样的事情:

module.directive('myDirective', [
  function() {
    return {
      restrict: 'E',
      link: function(scope, el, attrs) {
        scope.keyPressed = 'no press :(';
        // For listening to a keypress event with a specific code
        scope.$on('keypress:13', function(onEvent, keypressEvent) {
          scope.keyPressed = 'Enter';
        });
        // For listening to all keypress events
        scope.$on('keypress', function(onEvent, keypressEvent) {
          if (keypress.which === 120) {
            scope.keyPressed = 'x';
          }
          else {
            scope.keyPressed = 'Keycode: ' + keypressEvent.which;
          }
        });
      },
      template: '<h1>{{keyPressed}}</h1>'
    };
  }
]);
Run Code Online (Sandbox Code Playgroud)

  • 根据上面的代码,该指令将事件绑定到window.document($ document)元素,而它可以附加到任何DOM标记,而不仅仅是<body>,因为没有验证.在这种情况下,可以销毁附加指令的元素,但仍然保留绑定事件侦听器.我建议要么进行一些验证(将元素限制为<body>),要么实现使用$ scope.on('destroy')取消绑定事件监听器的方法. (6认同)
  • 路要走,真的很干净. (2认同)
  • 它绑定到$ document,而不是元素,对于我在div上获取关键事件起作用.+1表示如何注入$ document. (2认同)

use*_*062 27

用途$document.bind:

function FooCtrl($scope, $document) {
    ...
    $document.bind("keypress", function(event) {
        console.debug(event)
    });
    ...
}
Run Code Online (Sandbox Code Playgroud)


A. *_*ray 20

我还不能保证它,但我已经开始看看AngularHotkeys.js了:

http://chieffancypants.github.io/angular-hotkeys/

一旦我深入了解它,将更新更多信息.

更新1:哦有一个nuget包:angular-hotkeys

更新2:实际上非常容易使用,只需在你的路线或我正在做的,在你的控制器中设置你的绑定:

hotkeys.add('n', 'Create a new Category', $scope.showCreateView);
hotkeys.add('e', 'Edit the selected Category', $scope.showEditView);
hotkeys.add('d', 'Delete the selected Category', $scope.remove);
Run Code Online (Sandbox Code Playgroud)


Jas*_*son 10

这是我用jQuery完成的方法 - 我认为有更好的方法.

var app = angular.module('angularjs-starter', []);

app.directive('shortcut', function() {
  return {
    restrict: 'E',
    replace: true,
    scope: true,
    link:    function postLink(scope, iElement, iAttrs){
      jQuery(document).on('keypress', function(e){
         scope.$apply(scope.keyPressed(e));
       });
    }
  };
});

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  $scope.keyCode = "";
  $scope.keyPressed = function(e) {
    $scope.keyCode = e.which;
  };
});
Run Code Online (Sandbox Code Playgroud)
<body ng-controller="MainCtrl">
  <shortcut></shortcut>
  <h1>View keys pressed</h1>
  {{keyCode}}
</body>
Run Code Online (Sandbox Code Playgroud)

Plunker演示


Tom*_*und 10

以下是键盘快捷键的AngularJS服务示例:http://jsfiddle.net/firehist/nzUBg/

它可以像这样使用:

function MyController($scope, $timeout, keyboardManager) {
    // Bind ctrl+shift+d
    keyboardManager.bind('ctrl+shift+d', function() {
        console.log('Callback ctrl+shift+d');
    });
}
Run Code Online (Sandbox Code Playgroud)

更新:我现在正在使用角度热键.


Bla*_*wen 7

作为指令

这基本上是在Angular文档代码中完成的,即按下/开始搜索.

angular
 .module("app", [])
 .directive("keyboard", keyboard);

function keyboard($document) {

  return {
    link: function(scope, element, attrs) {

      $document.on("keydown", function(event) {

      // if keycode...
      event.stopPropagation();
      event.preventDefault();

      scope.$apply(function() {            
        // update scope...          
      });
    }
  };
}
Run Code Online (Sandbox Code Playgroud)

使用键盘指令插入

http://plnkr.co/edit/C61Gnn?p=preview


作为服务

将该指令转换为服务非常简单.唯一真正的区别是范围不会在服务上公开.要触发摘要,您可以引入$rootScope或使用a $timeout.

function Keyboard($document, $timeout, keyCodes) {
  var _this = this;
  this.keyHandlers = {};

  $document.on("keydown", function(event) {        
    var keyDown = _this.keyHandlers[event.keyCode];        
    if (keyDown) {
      event.preventDefault();
      $timeout(function() { 
        keyDown.callback(); 
      });          
    }
  });

  this.on = function(keyName, callback) {
    var keyCode = keyCodes[keyName];
    this.keyHandlers[keyCode] = { callback: callback };
    return this;
  };
}
Run Code Online (Sandbox Code Playgroud)

您现在可以使用该keyboard.on()方法在控制器中注册回调.

function MainController(keyboard) {

  keyboard
    .on("ENTER",  function() { // do something... })
    .on("DELETE", function() { // do something... })
    .on("SHIFT",  function() { // do something... })
    .on("INSERT", function() { // do something... });       
}
Run Code Online (Sandbox Code Playgroud)

Plunk的替代版本使用服务

http://plnkr.co/edit/z9edu5?p=preview