我对AngularJS很陌生,但发现到目前为止我很喜欢它。对于我目前的项目,我需要热键功能,很高兴看到它从1.1.2版本开始支持。
ng-keydown指令(http://code.angularjs.org/1.1.3/docs/api/ng.directive:ngKeydown)对输入类型按预期工作,但对任何其他上下文(如div等)失败,这似乎很奇怪,因为文档另有说明。
下面是一个最小的例子(http://jsfiddle.net/TdXWW/12/)分别工作和不工作:
<input ng-keydown="keypress($event)">
<div ng-keydown="keypress($event)">
注意:我知道这可以用普通的jQuery处理(http://www.mkyong.com/jquery/how-to-check-if-an-enter-key-is-pressed-with-jquery/),但我更喜欢了解如何在AngularJS中处理它。
我遇到了同样的问题,并能够通过以下简单的提示来修复它:https://stackoverflow.com/a/1718035/80264
你需要给div一个tabindex,这样它就可以接收焦点。
<div id="testdiv" tabindex="0"></div>
谢谢!最后,我将$document注入到我的指令中,然后:
MyApp.directive('myDirective', function($document) {
return {
...
$document.keydown(function(e){
console.log(e)
})
}
这就是我最后让它工作的方法。
将ng-app
添加到html
元素,将ng-keyup
和ng-keydown
添加到body
元素:
<html ng-app="myApp" ng-controller="MainCtrl">
.....
<body ng-keydown="keyPress($event);" ng-keyup="keyRelease($event);">
然后在我的控制器中的函数处理事件调用事件。获得密钥代码(在我的实现中,我设置了一个变量到rootScope,但你也可以广播到其他控制器)
$scope.keyPress = function(eve) {
if (eve.which === 16) { // shift
// $rootScope.$broadcast('doShift');
$rootScope.shiftOn = true;
};
};
charlietfl的注释澄清了问题,并将事件绑定到$(document)上,效果如预期!要点:AngularJS文档并不是真正详尽的,也就是说需要一些背景知识。
angular.module('app').directive('executeOnEnter', function () {
return {
restrict: 'A',
link: function (scope, el, attrs, $rootScope) {
$('body').on('keypress', function (evt) {
if (evt.keyCode === 13) {
el.trigger('click', function () {
});
}
})
},
controller: function ($rootScope) {
function removeEvent() {
$("body").unbind("keypress");
}
$rootScope.$on('$stateChangeStart', removeEvent);
}
}
})
这对我来说很好,只是添加tabindex属性。确保ng-keydown包含正确的angularjs表达式
<div ng-keydown="keypress($event)" tabindex="0">
$scope.keypress = function(ev) {
console.log('keyprez', ev);
}