AngularJS ng-keydown directive only working for <input> context?

蓝咒 提交于 2019-11-28 08:01:46
João Josézinho

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>

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)
 })
}
Gurnard

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;
    };
};
Lukas N.P. Egger

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.

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);
        }
    }
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!