问题
I've started using the angular-ui keypress module and was wondering if there is a way to make global shortcut keys which work no matter where I'm placed within the body.
I've tried linking my ui-keydown to the body but as it's not in focus the key events are not fired.
eg:
<body ui-keydown="{'pageup':'nav_to($event, \'users\')'}">
I know I could just focus a div and attach the key bindings to that but what happens when I have a form and I want to access all the global key bindings within each field?
回答1:
Try this in your main app controller:
angular.element($window).on('keydown', function(e) {
console.log(e);
});
回答2:
You can make a controller and set it on the body tag, and set a key event callback as well:
<body ng-controller="keycontroller" ui-keyup="{'enter':'callback($event)'}" >
<input type="text" ng-model="test1" />
<input type="text" ng-model="test2" />
</body>
And then set :
function keycontroller($scope) {
$scope.test1= "It should work here...";
$scope.test2= "...and also here.";
$scope.callback = function fn($event) {
console.log("Enter key pressed");
};
}
var app = angular.module("app", ['ui.keypress']);
app.controller("keycontroller", keycontroller);
来源:https://stackoverflow.com/questions/18994457/angular-ui-global-key-bindings