Binding keyboard events in AngularJS
angularjs, javascript, keyboard
Solution
Where are you trying to capture these events? Is it on a global scale or just something specific?
Here's an example of limiting an input field for date keys.
Then you just decorate your input tag like
Html
<input type="text" date-keys />
angular directive
angularDirectivesApp.directive('dateKeys', function () {
return {
restrict: 'A',
link: function (scope, element, attrs, controller) {
debugger;
element.on('keydown', function (event) {
if (isNumericKeyCode(event.keyCode) || isForwardSlashKeyCode(event.keyCode) || isNavigationKeycode(event.keyCode))
return true;
return false;
});
}
}
function isNumericKeyCode(keyCode) {
return (event.keyCode >= 48 && event.keyCode <= 57)
|| (event.keyCode >= 96 && event.keyCode <= 105);
}
function isForwardSlashKeyCode(keyCode) {
return event.keyCode === 191;
}
function isNavigationKeycode(keyCode) {
switch (keyCode) {
case 8: //backspace
case 35: //end
case 36: //home
case 37: //left
case 38: //up
case 39: //right
case 40: //down
case 45: //ins
case 46: //del
return true;
default:
return false;
}
}
});
Problem
What is the ideal way to bind Keyboard keypress events, if you're using AngularJS? Right now I'm setting the mapping the keyboard events inside of a controller... ``` ngApp.controller('MainController', function MainController($scope) { $scope.keyEvents = function() { if($('calculator').hasClass('open')) { switch(e.keyCode) { case 8: calc.deleteDigit(); return; case 13: calc.equals(); *etc., etc.* } } var $article = $("article"); var $articleScrollTop = $article.scrollTop(); //PageDown if(e.keyCode == 34) { $('article').animate({ scrollTop: ($articleScrollTop + 480 + i++) }, 500); } //PageUp if(e.keyCode == 33) { $article.animate({ scrollTop: ($articleScrollTop - 480 - i++) }, 500); } } } ``` I'm beginning to think that there is a best practice when it comes to attaching keyboard events inside of an AngularJS app. Should I be using `element.bind` and setting up the keyboard events inside of the corresponding directives instead? Thanks in advance for your help!