runtimeZero
runtimeZero

Reputation: 28046

keydown and keypress events not working in angular

I have a directive where I am trying to bind the keypress and keydown events but for some reason they will not register.

element.bind("keydown keypress", function (event) {
    console.log("here");
});

Any clues why this could be ?

If you look at the file selectMe.js in this plnkr you can see the binding.

Upvotes: 1

Views: 3326

Answers (2)

AxeEffect
AxeEffect

Reputation: 7431

Try adding tabindex="0" to the <table>. With this you make the <table> focusable with a click or pressing tab. However you may be interested on starting listening to key events as soon as the page is loaded. Then you should bind the event to document:

angular.element(document).bind(...)

Upvotes: 2

Jason Goemaat
Jason Goemaat

Reputation: 29194

If you bind to the table element, you won't get key events because the table doesn't have focus. See this question for info on which elements can have focus.

The events do bubble up however, so you can either add an invisible input or anchor element and get the keyboard events when they bubble up, or just listen on your document element to get any unhandled events. You can also check the ctrlKey flag on the key event instead of tracking the control key yourself:

var doc = angular.element(document);
doc.on('keyup', function(e) {
  if (e.ctrlKey) {
    if (e.keyCode === cKey) {
        $scope.valueToBeCopied = e.target.value;
        console.log('copy: valueToBeCopied: ' + $scope.valueToBeCopied);
      }
      if (e.keyCode === vKey) {
        e.target.value = $scope.valueToBeCopied;
        console.log('paste: valueToBeCopied: ' + $scope.valueToBeCopied);
      }
    }
});

I don't know how much that helps though with what you seem to be attempting. You'll have to track which element has the virtual 'focus' some other way.

Upvotes: 0

Related Questions