簡體   English   中英

angular.js監聽按鍵作為按鈕的快捷方式

[英]angular.js listen for keypress as shortcut for button

我的第一個角應用程序是一個非常基本的調查工具。 我有多個選擇題,每個答案都有一個按鈕,還有一個基本功能,可以按下按鈕點擊每個答案,如下所示:

ng-click="logAnswer(answer.id)"

我正在尋找的是能夠在文檔中添加一個按鍵事件,該事件將監聽1,2,3,4,5的鍵盤響應,該響應與按鈕選項匹配並調用相同的功能。

在搜索時,我只能在特定輸入字段具有焦點時找到與按鍵相關的響應,這對我沒有幫助。 我確實在這篇文章中找到了針對Angular.js按鍵事件和工廠的OP響應,這些事件和工廠似乎朝着正確的方向前進,但我無法理解我如何得到他的指令來調用我的函數。

我已將指令包含在我的js中:

angular.module('keypress', []).directive('keypressEvents', 
  function($document, $rootScope) {
    return {
      restrict: 'A',
      link: function() {
        $document.bind('keypress', function(e) {
           $rootScope.$broadcast('keypress',e , String.fromCharCode(e.which));
        });
     }
   }
})

但我不確定如何使用控制器中的鍵綁定對象:

function keyedS(key, parent_evt, evt){
      // key is the key that was pressed
      // parent_evt is the keypress event
      // evt is the focused element object
}
$scope.keyBindings = {
    's': keyedS
}

如何使鍵綁定對象偵聽我正在偵聽的鍵並啟動我需要的功能?

謝謝

捕獲控制器中的rootscope發出的事件:

$rootScope.$on('keypress', function (e, a, key) {
    $scope.$apply(function () {
        $scope.key = key;
    });
})

然后你的key在控制器中使用。

這是一個小提琴

如果您堅持使用AngularJS來檢測按鍵事件, ngKeypress就是您想要使用的。

<!-- you can, for example, specify an expression to evaluate -->
<input ng-keypress="count = count + 1" ng-init="count=0">

<!-- or call a controller/directive method and pass $event as parameter.
     With access to $event you can now do stuff like 
     finding which key was pressed -->
<input ng-keypress="changed($event)">

您可以查看ngKeypress的文檔以獲取更多信息。 您可能還想查看ngKeydownngKeyup指令。

有人已經創建了一個特定的鍵盤快捷鍵AngularJS模塊,看看:

https://github.com/chieffancypants/angular-hotkeys#angular-hotkeys-

特定按鍵/鍵控功能

是否可以僅在按下特定鍵時調用函數,如空格鍵? 我看過ngKeydown

 <input ng-keydown="function()"> 

但這會在每個按鍵上調用該函數,是否可以看到按下了哪個鍵,可能在函數內?

使用ng-keydown指令公開的$event對象。

 <input ng-keydown="fn($event)">

JS

 $scope.fn = function (event) {
     $scope.keyCode = event.keyCode;
     if (event.keyCode == 32) {
         console.log("spacebar pressed");
     };
 });

PLNKR上DEMO

有關$event對象的更多信息,請參閱AngularJS Developer Guide - $ event

看一下ngKeyup指令。 ngKeyUp的描述

根據按鍵,使用一系列函數來完成所需的各種功能

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM