使用AngularJS偵測按鍵事件
2015-09-03 10:49:08

AngualrJs提供了ng-keyup, ng-keydown, ng-keypress可以用來偵測按鍵事件。

範例

html

<div ng-controller="MyCtrl">
  <input.search-input ng-keydown="onSearchKeyDown($event)">
</div>

js

angular.module("exApp").controller("MyCtrl", function ($scope)
{
    $scope.onSearchKeyDown = function (event) {
      # do something ...
      $scope.key = event.keyCode
    };
}

注意AngularJS的event會被傳遞至上層的DOM,例如:

html

<div ng-controller="MyCtrl">
  <div.menu-panel ng-keydown="onMenuKeyDown($event)">
    <input.search-input ng-keydown="onSearchKeyDown($event)">
  </div>
</div>

js

angular.module("exApp").controller("MyCtrl", function ($scope)
{
    $scope.onMenuKeyDown = function (event) {
      $scope.keyMenu = event.keyCode
    };
    $scope.onSearchKeyDown = function (event) {
      $scope.keySearch = event.keyCode
    };
}

這時可以加上event.stopPropagation();來停止事件的傳遞。

angular.module("exApp").controller("MyCtrl", function ($scope)
{
    $scope.onMenuKeyDown = function (event) {
      $scope.keyMenu = event.keyCode
    };
    $scope.onSearchKeyDown = function (event) {
      $scope.keySearch = event.keyCode
      event.stopPropagation();
    };
}