小编典典

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

angularjs

我想应该使用伪指令,但是将伪指令添加到正文中却侦听文档中的事件似乎很奇怪。

什么是正确的方法?

更新:找到了AngularJSUI,并看到了它们对keypress指令实现。


阅读 363

收藏
2020-07-04

共1个答案

小编典典

这就是我使用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>

plnkr演示

2020-07-04