3

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!

fauverism
  • 1,970
  • 3
  • 33
  • 59
  • 1
    If you don't mind adding a dependency to your project, [AngularUI](http://angular-ui.github.io/) has a directive that [binds to keypress events](http://angular-ui.github.io/ui-utils/#keypress). – lostriebo Feb 25 '14 at 22:35
  • Thanks @lostriebo going to give this a shot. – fauverism Feb 26 '14 at 15:40

1 Answers1

6

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;
    }
}
});
VtoCorleone
  • 16,813
  • 5
  • 37
  • 51