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:
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.