What is AngularJS way to create global keyboard shortcuts?

后端 未结 12 2129
一整个雨季
一整个雨季 2020-11-30 22:04

I suppose that I should use directive, but it seems strange to add directive to body, but listen events on document.

What is a proper way to do this?

UPDATE:

12条回答
  •  野性不改
    2020-11-30 22:56

    I made a service for shortcuts.

    It looks like:

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

    And I injected it into a controller:

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

    It works, but you may notice that I inject $element and $document into the controller.

    It's a bad controller practice and violates the 'Dont EVER access $element in the controller' convention.

    I should put it into directive, then use 'ngKeydown' and $event to trigger the service.

    But I think the service is fine and I will rework the controller sooner.


    updated:

    It seems like 'ng-keydown' only works in input tags.

    So I just write a directive and inject $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);
             }
           })
         }
       }
      })
    

    It's better.

提交回复
热议问题