angular.js 侦听按键作为按钮的快捷方式 [英] angular.js listen for keypress as shortcut for button

查看:29
本文介绍了angular.js 侦听按键作为按钮的快捷方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的第一个 Angular 应用程序是一个非常基本的调查工具.我有多项选择题,每个答案都有一个按钮,还有一个基本功能,可以在单击按钮时记录每个答案,如下所示:

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 on button click like this:

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

我正在寻找的是能够向文档添加一个按键事件,该事件将侦听与按钮选择匹配并调用相同函数的 1、2、3、4、5 的键盘响应.

What I'm looking for is to be able to add a keypress event to the document that will listen for a keyboard response of 1, 2, 3, 4, 5 which matches up with the button choices and calls the same function.

在四处搜索时,我只能在特定输入字段获得焦点后找到与按键相关的响应,这对我没有帮助.我确实在这篇文章中找到了 OP 的响应 Angular.js 按键事件和工厂这似乎朝着正确的方向前进,但我无法弄清楚如何让他的指令调用我的函数.

In searching around I can only find responses that relate to keypresses once a particular input field has focus, which doesn't help me. I did find the OPs response on this post Angular.js keypress events and factories which seems to be heading in the right direction, but I just can't work out how I get his directive to call my function.

我已经在我的 js 中包含了指令:

I've included the directive in my 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));
        });
     }
   }
})

但我不确定如何使用控制器中的键绑定对象:

but I'm not sure how I make use of the keybinding object within my controller:

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
}

如何让键绑定对象监听我正在监听的键并触发我需要的功能?

How do I make the keybinding object listen for the keys I'm listening for and fire-off the function that I need?

谢谢

推荐答案

捕获控制器中 rootscope 发出的事件:

Catch the event emitted by the rootscope in your controller:

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

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

key is then yours to use in the controller.

这是一个小提琴

这篇关于angular.js 侦听按键作为按钮的快捷方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆