我的第一个 Angular 应用程序是一个非常基本的调查工具。我有多个选择题,每个答案都有一个按钮,还有一个基本功能,可以在单击按钮时记录每个答案,如下所示:
ng-click="logAnswer(answer.id)"
我正在寻找的是能够将按键事件添加到文档中,该事件将监听 1、2、3、4、5 的键盘响应,该响应与按钮选择相匹配并调用相同的函数.
在四处搜索时,一旦特定输入字段获得焦点,我只能找到与按键相关的响应,这对我没有帮助。我确实在这篇文章中找到了 OP 的回复 Angular.js keypress events and factories这似乎在朝着正确的方向前进,但我就是不知道如何让他的指令调用我的函数。
我已将指令包含在我的 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));
});
}
}
})
但我不确定如何在我的 Controller 中使用键绑定(bind)对象:
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
}
如何让键绑定(bind)对象监听我正在监听的键并触发我需要的功能?
谢谢
最佳答案
在您的 Controller 中捕获根作用域发出的事件:
$rootScope.$on('keypress', function (e, a, key) {
$scope.$apply(function () {
$scope.key = key;
});
})
key
就是你在 Controller 中使用的了。
这是一个 fiddle
关于javascript - angular.js 监听按键作为按钮的快捷方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24621833/