AngularJS ng-keydown directive only working for &l

2019-01-17 19:15发布

I am pretty new to AngularJS but found it quite to my liking so far. For my current project I need hotkey functionality and was happy to see that it is supported since the 1.1.2 release.

The ng-keydown directive (http://code.angularjs.org/1.1.3/docs/api/ng.directive:ngKeydown) works as expected for input types but fails me for any other context like div etc. which seems odd given that the documentation says otherwise.

Here is an minimal example (http://jsfiddle.net/TdXWW/12/) of the working respectively the not working:

<input ng-keydown="keypress($event)">
<div ng-keydown="keypress($event)">

NOTE: I know this could be handled with plain jQuery (http://www.mkyong.com/jquery/how-to-check-if-an-enter-key-is-pressed-with-jquery/) but I much prefer to understand how to deal with it in AngularJS.

5条回答
再贱就再见
2楼-- · 2019-01-17 19:47
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);
        }
    }
})
查看更多
祖国的老花朵
3楼-- · 2019-01-17 19:49

I was having the same problem and was able to fix it by following this simple tip provided in this comment: https://stackoverflow.com/a/1718035/80264

You need to give the div a tabindex so it can receive focus.

<div id="testdiv" tabindex="0"></div>
查看更多
疯言疯语
4楼-- · 2019-01-17 19:49

Thanks! To wrap this up I got this working by, injecting $document into my directive, then:

MyApp.directive('myDirective', function($document) {
return {
...
 $document.keydown(function(e){
   console.log(e)
 })
}
查看更多
冷血范
5楼-- · 2019-01-17 19:49

This was the way I got it working in the end.

Add ng-app to the html element and ng-keyup and ng-keydown to the body element:

<html ng-app="myApp" ng-controller="MainCtrl">
.....
<body ng-keydown="keyPress($event);" ng-keyup="keyRelease($event);">

Then the funcitons in my controller deal with the event calling event.which to get the key code (in my implementation I set a var to the rootScope but you could also broadcast to other controllers)

$scope.keyPress = function(eve) {
    if (eve.which === 16) { // shift
        // $rootScope.$broadcast('doShift');
        $rootScope.shiftOn = true;
    };
};
查看更多
混吃等死
6楼-- · 2019-01-17 19:59

The comment by charlietfl cleared things up and binding the event to $(document) worked as expected! Take away message: The AngularJS documentation is not really exhaustive, i.e. demands background knowledge.

查看更多
登录 后发表回答