angular.js listen for keypress as shortcut for button

前端 未结 5 843
离开以前
离开以前 2021-01-02 08:03

My first ever angular application is a pretty basic survey tool. I have multiple choice questions, with a button for each answer and a basic function that logs each answer o

5条回答
  •  生来不讨喜
    2021-01-02 08:34

    function on specific keypress/keydown

    Is is possible to call a function only when a specific key is pressed, like the spacebar? I've looked into ngKeydown

    
    

    But this will call the function on every keypress, is it possible to see what key was pressed, maybe within the function?

    Use the $event object exposed by the ng-keydown directive.

     
    

    JS

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

    The DEMO on PLNKR

    For more information on the $event object, see AngularJS Developer Guide - $event

提交回复
热议问题