什么是 AngularJS 创建全局键盘快捷键的方法? [英] What is AngularJS way to create global keyboard shortcuts?
本文介绍了什么是 AngularJS 创建全局键盘快捷键的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想我应该使用指令,但在正文中添加指令似乎很奇怪,但在文档上监听事件.
I suppose that I should use directive, but it seems strange to add directive to body, but listen events on document.
这样做的正确方法是什么?
What is a proper way to do this?
更新:找到了 AngularJS UI 并看到了他们对 keypress 指令的实现.
UPDATE: Found AngularJS UI and saw their realization of keypress directive.
推荐答案
以下是我使用 jQuery 完成此操作的方法 - 我认为有更好的方法.
Here's how I've done this with jQuery - I think there's a better way.
var app = angular.module('angularjs-starter', []);
app.directive('shortcut', function() {
return {
restrict: 'E',
replace: true,
scope: true,
link: function postLink(scope, iElement, iAttrs){
jQuery(document).on('keypress', function(e){
scope.$apply(scope.keyPressed(e));
});
}
};
});
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.keyCode = "";
$scope.keyPressed = function(e) {
$scope.keyCode = e.which;
};
});
<body ng-controller="MainCtrl">
<shortcut></shortcut>
<h1>View keys pressed</h1>
{{keyCode}}
</body>
这篇关于什么是 AngularJS 创建全局键盘快捷键的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文