Keyboard event binding in AngularJS

What is the ideal way to bind keyboard keystroke events if you are using AngularJS?

Now I'm setting up the display of keyboard events inside the 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 starting to think that there is best practice when it comes to adding keyboard events inside an AngularJS application.

Should I use element.bindand configure keyboard events inside the corresponding directives instead?

Thanks in advance for your help!

+3
source share
1 answer

Where are you trying to capture these events? Is it global or just something specific?

Here is an example of an input field restriction for date keys.

Then you simply decorate your input tag, for example

HTML

<input type="text" date-keys />

angular

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;
    }
}
});
+6

All Articles