Search code examples
angularjskeyboard-eventsuppercaselowercase

angularjs $event get the same code for uppercase and lowercase for a key


i'm struggling to create hotkeys using angularjs $event. i need to simplify the codes for uppercase and lowercase. however i viewed from the console.log($event) they have different keyCode.

p is 112 P is 80

HTML:

<body ng-app="pointofsale" ng-controller="PointofSaleCtrl" ng-keypress="hotKeyEvent($event)">

Javascript:

$scope.hotKeyEvent = function(data){
    console.log(data);

    switch(data.keyCode){
        case 112: // p

            break;
        case 80:  // P

            break;

        default:
            console.log('No key associated')

    }
}

What am i missing here? i don't want to create two conditions for the same character but different case.

Appreciate any help, Thanks!


Solution

  • You could simplify your switch by grouping the case statements

    like this:

    switch(data.keyCode){
    
             case 112: // p
             case 80:  // P
    
                break;       
    
            default:
                console.log('No key associated')
        }
    

    It's known as falling through - essentially, anything matched will continue to run until a break is hit.

    Makes maintenance quite a bit easier too.