AngularJS 创建全局键盘快捷键的方法是什么?
IT技术
javascript
angularjs
2021-02-25 15:12:17
6个回答
我会说更合适的方法(或“Angular 方法”)是将它添加到指令中。这是一个简单的方法(只需将keypress-events
属性添加到<body>
):
angular.module('myDirectives', []).directive('keypressEvents', [
'$document',
'$rootScope',
function($document, $rootScope) {
return {
restrict: 'A',
link: function() {
$document.bind('keypress', function(e) {
console.log('Got keypress:', e.which);
$rootScope.$broadcast('keypress', e);
$rootScope.$broadcast('keypress:' + e.which, e);
});
}
};
}
]);
在您的指令中,您可以简单地执行以下操作:
module.directive('myDirective', [
function() {
return {
restrict: 'E',
link: function(scope, el, attrs) {
scope.keyPressed = 'no press :(';
// For listening to a keypress event with a specific code
scope.$on('keypress:13', function(onEvent, keypressEvent) {
scope.keyPressed = 'Enter';
});
// For listening to all keypress events
scope.$on('keypress', function(onEvent, keypressEvent) {
if (keypress.which === 120) {
scope.keyPressed = 'x';
}
else {
scope.keyPressed = 'Keycode: ' + keypressEvent.which;
}
});
},
template: '<h1>{{keyPressed}}</h1>'
};
}
]);
使用$document.bind
:
function FooCtrl($scope, $document) {
...
$document.bind("keypress", function(event) {
console.debug(event)
});
...
}
我现在还不能保证,但我已经开始研究 AngularHotkeys.js:
http://chieffancypants.github.io/angular-hotkeys/
一旦我开始使用它,将更新更多信息。
更新 1:哦,有一个 nuget 包:angular-hotkeys
更新 2:实际上非常易于使用,只需在您的路线中或像我一样在您的控制器中设置您的绑定:
hotkeys.add('n', 'Create a new Category', $scope.showCreateView);
hotkeys.add('e', 'Edit the selected Category', $scope.showEditView);
hotkeys.add('d', 'Delete the selected Category', $scope.remove);
这是我使用 jQuery 完成此操作的方法 - 我认为有更好的方法。
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 服务示例:http : //jsfiddle.net/firehist/nzUBg/
然后可以像这样使用它:
function MyController($scope, $timeout, keyboardManager) {
// Bind ctrl+shift+d
keyboardManager.bind('ctrl+shift+d', function() {
console.log('Callback ctrl+shift+d');
});
}
更新:我现在使用angular-hotkeys代替。