angular.js listen for keypress as shortcut for button

前端 未结 5 844
离开以前
离开以前 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:20

    Catch the event emitted by the rootscope in your controller:

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

    key is then yours to use in the controller.

    Here's a fiddle

    0 讨论(0)
  • 2021-01-02 08:32

    Someone already created a specific Keyboard shortcuts AngularJS module, have a look :

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

    0 讨论(0)
  • 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

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

    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.

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

    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

    0 讨论(0)
  • 2021-01-02 08:36

    Take a look at the ngKeyup directive. Description of ngKeyUp

    Use an array of functions for the various functions you need based on the keypress

    0 讨论(0)
  • 2021-01-02 08:40

    If you insist on using AngularJS to detect the keypress event, ngKeypress is what you want to use.

    <!-- 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)">
    

    You can check out the documentation for ngKeypress for more information. You might also want to check out the ngKeydown and ngKeyup directives.

    0 讨论(0)
提交回复
热议问题