I need to redirect the user to a specific route when he/she presses a specific key from the keyboard. My question is:
In the light of separation of concerns and AngularJS best practices, should this code remain on a directive or on a service?
I'm aware that directives should be used to manipulate DOM. So, with that in mind, I created the service below:
myApp.factory("KeyPressEvents", ['$rootScope', '$document', '$location', function($rootScope, $document, $location){
return $document.bind("keypress", function(event){
if(event.charCode==112){
$rootScope.$apply(function(){
$location.path('/route2');
});
}
});
}]);
In the code above, the user is redirected to '/route2' whenever he presses P on the keyboard.
On the other hand, researching on stackoverflow, I realized that some answers recommend the use directives to do almost the same thing:
How to use a keypress event in AngularJS?
Binding keyboard events in AngularJS
And that is why I still don't quite get it. Any thoughts on that issue? Thanks!