简体   繁体   中英

ng-keydown doesn't work in angular

I try to bind arrow keydown event to the document, but it doesn't work in angular. code:

function CubeCtrl($scope, $locale) {

$scope.click = function(){
    alert("click")
}
$scope.keydown = function(){
    alert("keydown")
}

}

html:

<body ng-app ng-controller="CubeCtrl" ng-click="click()" ng-keydown="keydown()">

and here is jsfiddle

This is probably Angular version issue.

You can chcek this solution: UI Utils

Or best way is to write your own directive for this event:

Directive:

   var mod = angular.module('mydirectives');
mod.directive('ngKeydown', function() {
    return {
        restrict: 'A',
        link: function(scope, elem, attrs) {
             // this next line will convert the string
             // function name into an actual function
             var functionToCall = scope.$eval(attrs.ngKeydown);
             elem.on('keydown', function(e){
                  // on the keydown event, call my function
                  // and pass it the keycode of the key
                  // that was pressed
                  // ex: if ENTER was pressed, e.which == 13
                  functionToCall(e.which);
             });
        }
    };
});

HTML

<input type="text" ng-keydown="onKeydown">

The ngKeydown directive is not supported by version 1.1.1. You should be using atleast version 1.1.2 for using this directive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM