首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >创建全局键盘快捷键的AngularJS方法是什么?

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

Stack Overflow用户
提问于 2013-02-24 03:13:23
回答 7查看 62.6K关注 0票数 77

我想我应该使用指令,但是将指令添加到body中似乎有些奇怪,但是监听文档上的事件。

做这件事的正确方法是什么?

更新:创建了AngularJS UI,并看到了按键指令的their实现。

EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2013-02-24 03:58:39

以下是我如何使用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;
  };
});
<body ng-controller="MainCtrl">
  <shortcut></shortcut>
  <h1>View keys pressed</h1>
  {{keyCode}}
</body>

Plunker demo

票数 10
EN

Stack Overflow用户

发布于 2013-10-17 03:33:47

我会说一种更恰当的方式(或"Angular方式“)是将其添加到指令中。下面是一个简单的方法(只需向<body>添加keypress-events属性):

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);
        });
      }
    };
  }
]);

在您的指令中,您可以简单地执行以下操作:

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>'
    };
  }
]);
票数 70
EN

Stack Overflow用户

发布于 2013-10-07 01:57:25

使用$document.bind

function FooCtrl($scope, $document) {
    ...
    $document.bind("keypress", function(event) {
        console.debug(event)
    });
    ...
}
票数 27
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15044494

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档