我想我应该使用指令,但是将指令添加到正文似乎很奇怪,但是在文档上监听事件。
这样做的正确方法是什么?
更新:找到 AngularJS UI 并看到他们对 keypress 指令的实现。
我想说一种更合适的方式(或“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代替。
作为指令
这基本上是在 Angular 文档代码中完成的,即按下/
开始搜索。
angular
.module("app", [])
.directive("keyboard", keyboard);
function keyboard($document) {
return {
link: function(scope, element, attrs) {
$document.on("keydown", function(event) {
// if keycode...
event.stopPropagation();
event.preventDefault();
scope.$apply(function() {
// update scope...
});
}
};
}
Plunk 使用键盘指令
http://plnkr.co/edit/C61Gnn?p=preview
作为服务
将该指令转换为服务非常容易。唯一真正的区别是范围没有在服务上公开。要触发摘要,您可以引入$rootScope
或使用$timeout
.
function Keyboard($document, $timeout, keyCodes) {
var _this = this;
this.keyHandlers = {};
$document.on("keydown", function(event) {
var keyDown = _this.keyHandlers[event.keyCode];
if (keyDown) {
event.preventDefault();
$timeout(function() {
keyDown.callback();
});
}
});
this.on = function(keyName, callback) {
var keyCode = keyCodes[keyName];
this.keyHandlers[keyCode] = { callback: callback };
return this;
};
}
您现在可以使用该keyboard.on()
方法在控制器中注册回调。
function MainController(keyboard) {
keyboard
.on("ENTER", function() { // do something... })
.on("DELETE", function() { // do something... })
.on("SHIFT", function() { // do something... })
.on("INSERT", function() { // do something... });
}
使用服务的替代版本的 Plunk
稍微短一点的答案就是看看下面的解决方案 3。如果您想了解更多选项,可以阅读全文。
我同意 jmagnusson 的观点。但我相信有更清洁的解决方案。与其将键与指令中的函数绑定,不如将它们绑定在 html 中,就像定义配置文件一样,并且热键应该是上下文的。
下面是使用带有自定义指令的鼠标陷阱的版本。(我不是这个小提琴的作者。)
var app = angular.module('keyExample', []);
app.directive('keybinding', function () {
return {
restrict: 'E',
scope: {
invoke: '&'
},
link: function (scope, el, attr) {
Mousetrap.bind(attr.on, scope.invoke);
}
};
});
app.controller('RootController', function ($scope) {
$scope.gotoInbox = function () {
alert('Goto Inbox');
};
});
app.controller('ChildController', function ($scope) {
$scope.gotoLabel = function (label) {
alert('Goto Label: ' + label);
};
});
您将需要包含 mousetrap.js,并按如下方式使用它:
<div ng-app="keyExample">
<div ng-controller="RootController">
<keybinding on="g i" invoke="gotoInbox()" />
<div ng-controller="ChildController">
<keybinding on="g l" invoke="gotoLabel('Sent')" />
</div>
</div>
<div>Click in here to gain focus and then try the following key strokes</div>
<ul>
<li>"g i" to show a "Goto Inbox" alert</li>
<li>"g l" to show a "Goto Label" alert</li>
</ul>
</div>
该解决方案要求您包含 mousetrap.js,它是帮助您定义热键的库。
如果你想避免开发自己的自定义指令的麻烦,你可以查看这个库:
https://github.com/drahak/angular-hotkeys
还有这个
https://github.com/chieffancypants/angular-hotkeys
第二个提供了更多的功能和灵活性,即为您的应用程序自动生成热键备忘单。
更新:Angular ui 不再提供解决方案 3。
除了上述解决方案之外,angularui 团队还完成了另一种实现。但缺点是解决方案依赖于 JQuery 库,这不是 Angular 社区的趋势。(Angular 社区尝试只使用 angularjs 附带的 jqLite 并摆脱过度依赖的依赖。)这是链接
用法是这样的:
在您的 html 中,使用 ui-keydown 属性来绑定键和功能。
<div class="modal-inner" ui-keydown="{
esc: 'cancelModal()',
tab: 'tabWatch($event)',
enter: 'initOrSetModel()'
}">
在您的指令中,将这些函数添加到您的范围内。
app.directive('yourDirective', function () {
return {
restrict: 'E',
templateUrl: 'your-html-template-address.html'
link: function(){
scope.cancelModal() = function (){
console.log('cancel modal');
};
scope.tabWatch() = function (){
console.log('tabWatch');
};
scope.initOrSetModel() = function (){
console.log('init or set model');
};
}
};
});
在尝试了所有解决方案之后,我会推荐 Angular UI 团队实现的解决方案 3,它避免了我遇到的许多奇怪的小问题。
我为快捷方式提供了服务。
看起来像:
angular.module('myApp.services.shortcuts', [])
.factory('Shortcuts', function($rootScope) {
var service = {};
service.trigger = function(keycode, items, element) {
// write the shortcuts logic here...
}
return service;
})
我将它注入控制器:
angular.module('myApp.controllers.mainCtrl', [])
.controller('mainCtrl', function($scope, $element, $document, Shortcuts) {
// whatever blah blah
$document.on('keydown', function(){
// skip if it focused in input tag
if(event.target.tagName !== "INPUT") {
Shortcuts.trigger(event.which, $scope.items, $element);
}
})
})
它可以工作,但您可能会注意到我将 $element 和 $document 注入到控制器中。
这是一种不好的控制器做法,并且违反了“永远不要访问控制器中的 $element”约定。
我应该把它放入指令中,然后使用 'ngKeydown' 和 $event 来触发服务。
但我认为服务很好,我会尽快返工控制器。
更新:
似乎“ng-keydown”仅适用于输入标签。
所以我只写了一个指令并注入$document:
angular.module('myApp.controllers.mainCtrl', [])
.directive('keyboard', function($scope, $document, Shortcuts) {
// whatever blah blah
return {
link: function(scope, element, attrs) {
scope.items = ....;// something not important
$document.on('keydown', function(){
// skip if it focused in input tag
if(event.target.tagName !== "INPUT") {
Shortcuts.trigger(event.which, scope.items, element);
}
})
}
}
})
它更好。
从 ng-newsletter.com 后面的人那里查看这个例子;查看他们关于创建 2048 游戏的教程,它有一些使用键盘事件服务的不错的代码。
下面让您在控制器中编写所有快捷方式逻辑,该指令将处理其他所有事情。
指示
.directive('shortcuts', ['$document', '$rootScope', function($document, $rootScope) {
$rootScope.shortcuts = [];
$document.on('keydown', function(e) {
// Skip if it focused in input tag.
if (event.target.tagName !== "INPUT") {
$rootScope.shortcuts.forEach(function(eventHandler) {
// Skip if it focused in input tag.
if (event.target.tagName !== 'INPUT' && eventHandler)
eventHandler(e.originalEvent, e)
});
}
})
return {
restrict: 'A',
scope: {
'shortcuts': '&'
},
link: function(scope, element, attrs) {
$rootScope.shortcuts.push(scope.shortcuts());
}
};
}])
控制器
$scope.keyUp = function(key) {
// H.
if (72 == key.keyCode)
$scope.toggleHelp();
};
html
<div shortcuts="keyUp">
<!-- Stuff -->
</div>
你可以试试这个库,它使管理热键变得非常容易,当你浏览应用程序时它会自动绑定和取消绑定键
我不知道这是否是一种真正的角度方式,但我做了什么
$(document).on('keydown', function(e) {
$('.button[data-key=' + String.fromCharCode(e.which) + ']').click();
});
<div class="button" data-key="1" ng-click="clickHandler($event)">
ButtonLabel
</div>