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

时间:2013-02-23 19:13:23

标签: javascript angularjs

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

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

更新:找到AngularJS UI并看到their实现了keypress指令。

12 个答案:

答案 0 :(得分: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);
        });
      }
    };
  }
]);

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

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

答案 1 :(得分:27)

使用$document.bind

function FooCtrl($scope, $document) {
    ...
    $document.bind("keypress", function(event) {
        console.debug(event)
    });
    ...
}

答案 2 :(得分: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);

答案 3 :(得分: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');
    });
}

更新:我现在正在使用angular-hotkeys

答案 4 :(得分:9)

以下是我使用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

答案 5 :(得分: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...          
      });
    }
  };
}

使用键盘指令插入

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


即服务

将该指令转换为服务非常简单。唯一真正的区别是范围不会在服务上公开。要触发摘要,您可以引入$rootScope或使用$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;
  };
}

您现在可以使用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... });       
}

使用服务的替代版Plunk

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

答案 6 :(得分:4)

稍微简短的回答只是看下面的解决方案3。如果您想了解更多选项,可以阅读整篇文章。

我同意jmagnusson。但我相信有更清洁的解决方案。您应该能够在html中将它们绑定到配置文件中,而不是将键与命令中的函数绑定,而热键应该是上下文的。

  1. 以下是使用带有自定义指令的鼠标陷阱的版本。 (一世 不是这个小提琴的作者。)

    var app = angular.module('keyExample', []);
    
    app.directive('keybinding', function () {
        return {
            restrict: 'E',
            scope: {
                invoke: '&'
            },
            link: function (scope, el, attr) {
                Mousetrap.bind(attr.on, scope.invoke);
            }
        };
    });
    
    app.controller('RootController', function ($scope) {
        $scope.gotoInbox = function () {
            alert('Goto Inbox');
        };
    });
    
    app.controller('ChildController', function ($scope) {
        $scope.gotoLabel = function (label) {
            alert('Goto Label: ' + label);
        };
    });
    

    您需要包含mousetrap.js,并使用如下所示:

    <div ng-app="keyExample">
        <div ng-controller="RootController">
            <keybinding on="g i" invoke="gotoInbox()" />
            <div ng-controller="ChildController">
                <keybinding on="g l" invoke="gotoLabel('Sent')" />
            </div>
        </div>
        <div>Click in here to gain focus and then try the following key strokes</div>
        <ul>
            <li>"g i" to show a "Goto Inbox" alert</li>
            <li>"g l" to show a "Goto Label" alert</li>
        </ul>
    </div>
    

    http://jsfiddle.net/BM2gG/3/

    该解决方案要求您包含mousetrap.js,这是一个库 这有助于您定义热键。

  2. 如果您想避免开发自己的自定义的麻烦 指令,你可以查看这个lib:

    https://github.com/drahak/angular-hotkeys

    这个

    https://github.com/chieffancypants/angular-hotkeys

    第二个提供更多功能和灵活性,即 为您的应用自动生成热键备忘单。

  3. 更新:Angular ui不再提供解决方案3。

    1. 除上述解决方案外,还有另一项实施方案 由angularui团队。但缺点是解决方案取决于 JQuery lib不是角度社区中的趋势。 (角 社区尝试使用angularjs和jjLite 摆脱过度依赖的依赖。)这是链接

      http://angular-ui.github.io/ui-utils/#/keypress

    2. 用法如下:

      在你的html中,使用ui-keydown属性来绑定键和函数。

      <div class="modal-inner" ui-keydown="{
                              esc: 'cancelModal()',
                              tab: 'tabWatch($event)',
                              enter: 'initOrSetModel()'
                          }">
      

      在您的指令中,在您的范围中添加这些功能。

      app.directive('yourDirective', function () {
         return {
           restrict: 'E',
           templateUrl: 'your-html-template-address.html'
           link: function(){
              scope.cancelModal() = function (){
                 console.log('cancel modal');
              }; 
              scope.tabWatch() = function (){
                 console.log('tabWatch');
              };
              scope.initOrSetModel() = function (){
                 console.log('init or set model');
              };
           }
         };
      });
      

      在使用所有解决方案后,我会推荐Angular UI团队实施的解决方案3,它避免了我遇到的许多小问题。

答案 7 :(得分:1)

我为快捷方式提供了服务。

看起来像:

angular.module('myApp.services.shortcuts', [])
  .factory('Shortcuts', function($rootScope) {
     var service = {};
     service.trigger = function(keycode, items, element) {
       // write the shortcuts logic here...
     }

     return service;
})

我将它注入控制器:

angular.module('myApp.controllers.mainCtrl', [])
  .controller('mainCtrl', function($scope, $element, $document, Shortcuts) {
   // whatever blah blah

   $document.on('keydown', function(){
     // skip if it focused in input tag  
     if(event.target.tagName !== "INPUT") {
        Shortcuts.trigger(event.which, $scope.items, $element);
     }
   })
})

它可以工作,但您可能会注意到我将$ element和$ document注入控制器。

这是一个糟糕的控制器实践,违反了控制器约定中的'Dont EVER access $元素。

我应该将其置于指令中,然后使用'ngKeydown'和$ event来触发服务。

但我认为服务很好,我会尽快修改控制器。


<强>更新

似乎'ng-keydown'仅适用于输入标签。

所以我只写一个指令并注入$ document:

angular.module('myApp.controllers.mainCtrl', [])
  .directive('keyboard', function($scope, $document, Shortcuts) {
   // whatever blah blah
   return {
     link: function(scope, element, attrs) {
       scope.items = ....;// something not important

       $document.on('keydown', function(){
         // skip if it focused in input tag  
         if(event.target.tagName !== "INPUT") {
           Shortcuts.trigger(event.which, scope.items, element);
         }
       })
     }
   }
  })

更好。

答案 8 :(得分:0)

从那些伙伴behid ng-newsletter.com查看example;检查创建2048游戏的their tutorial,它有一些使用键盘事件服务的好代码。

答案 9 :(得分:0)

以下是让您在控制器中编写所有快捷逻辑,该指令将处理其他所有内容。

<强>指令

.directive('shortcuts', ['$document', '$rootScope', function($document, $rootScope) {
    $rootScope.shortcuts = [];

    $document.on('keydown', function(e) {
        // Skip if it focused in input tag.
        if (event.target.tagName !== "INPUT") {
            $rootScope.shortcuts.forEach(function(eventHandler) {
                // Skip if it focused in input tag.
                if (event.target.tagName !== 'INPUT' && eventHandler)
                    eventHandler(e.originalEvent, e)
            });
        }
    })

    return {
        restrict: 'A',
        scope: {
            'shortcuts': '&'
        },
        link: function(scope, element, attrs) {
            $rootScope.shortcuts.push(scope.shortcuts());
        }
    };
}])

<强>控制器

    $scope.keyUp = function(key) {
        // H.
        if (72 == key.keyCode)
            $scope.toggleHelp();
    };

<强> HTML

<div shortcuts="keyUp">
    <!-- Stuff -->
</div>

答案 10 :(得分:0)

你可以尝试这个库,它可以很容易地管理热键,它会在你导航应用程序时自动绑定和取消绑定键

angular-hotkeys

答案 11 :(得分:0)

我不知道它是否是一种真正有棱有角的方式,但我做了什么

$(document).on('keydown', function(e) {
    $('.button[data-key=' + String.fromCharCode(e.which) + ']').click();
});

<div class="button" data-key="1" ng-click="clickHandler($event)">
    ButtonLabel         
</div>