What is AngularJS way to create global keyboard shortcuts?

angularjs, javascript

Solution

Here's how I've done this with jQuery - I think there's a better way.

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

Problem

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: Found AngularJS UI and saw their realization of keypress directive.

Original source

Related problems