How to detect pressed keys on the click of AngularJS

后端 未结 5 1587
渐次进展
渐次进展 2021-02-07 00:44

I\'m using angularjs on a web application that I need to figure out how can I detect is keys like ctrl, shift or alt are pressed when I click so

5条回答
  •  旧时难觅i
    2021-02-07 01:31

    Take a look at this beautiful Stuff regarding AngularJS key handling

    So key code for Ctrl, shift, alt will be

    Ctrl - 17
    Alt - 18
    Shift - 16

    Working Demo

    HTML

    
    
    
      
      
    
    
    
      

    KEY DOWN RESULT: {{onKeyDownResult}}
    KEY UP RESULT: {{onKeyUpResult}}
    KEY PRESS RESULT: {{onKeyPressResult}}

    SCRIPT

    angular.module("mainModule", [])
      .controller("mainController", function ($scope)
      {
        // Initialization
        $scope.onKeyDownResult = "";
        $scope.onKeyUpResult = "";
        $scope.onKeyPressResult = "";
    
        // Utility functions
    
        var getKeyboardEventResult = function (keyEvent, keyEventDesc)
        {
          return keyEventDesc + " (keyCode: " + (window.event ? keyEvent.keyCode : keyEvent.which) + ")";
        };
    
        // Event handlers
        $scope.onKeyDown = function ($event) {
          $scope.onKeyDownResult = getKeyboardEventResult($event, "Key down");
        };
    
        $scope.onKeyUp = function ($event) {
          $scope.onKeyUpResult = getKeyboardEventResult($event, "Key up");
        };
    
        $scope.onKeyPress = function ($event) {
          $scope.onKeyPressResult = getKeyboardEventResult($event, "Key press");
        };
      });
    

提交回复
热议问题