如何在点击AngularJS时检测按下的键

如何在点击AngularJS时检测按下的键

问题描述:

我在网络应用程序中使用angularjs,我需要弄清楚当我点击某处时,我可以检测到如ctrl,shift或alt这样的按键。

I'm using angularjs on a webapplication that i need to figure out how can i detect is keys like ctrl, shift or alt are pressed when i click some where.

例如,使用jquery我可以通过访问Click函数参数来做到这一点。

for example, with jquery i can do that by accessing the Click function arguments.

是否有一些开箱即用的方法来获取有关角度的信息?

Is there some out-of-the-box way to obtain that information on angular?

看看这个美丽的东西 AngularJS键处理

因此,Ctrl,shift,alt的关键代码将是

So key code for Ctrl, shift, alt will be

Ctrl - 17

Alt - 18

Shift - 16

工作演示

Working Demo

HTML

<!DOCTYPE html>
<html>
<head>
  <script src="angular.js"></script>
  <script src="script.js"></script>
</head>

<body ng-app="mainModule">
  <div ng-controller="mainController">
    <label>Type something:
      <input type="text"
             ng-keydown="onKeyDown($event)"
             ng-keyup="onKeyUp($event)"
             ng-keypress="onKeyPress($event)" />
    </label><br />
    <strong>KEY DOWN RESULT:</strong> {{onKeyDownResult}}<br />
    <strong>KEY UP RESULT:</strong> {{onKeyUpResult}}<br />
    <strong>KEY PRESS RESULT:</strong> {{onKeyPressResult}}
  </div>
</body>
</html>

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");
    };
  });