Angular 1.x – issue with keydown handler function being called +1 extra time every call

  angularjs, javascript

I have an older angular.js file with the following structure:

$scope.clicked = function () {
  //logic here is called +1 every time
}

var keydownPress = function(e) {
  if (e.code === 'KeyP') {
    $scope.clicked();
  }
}

document.addEventListener('keydown', keydownPress);

My issue is that there are instances where if I open the same page in a new browser tab and press ‘P’ to call the function, it will call it an additional time. And it can keep incrementing so if I press it in another browser, it will call the function twice, etc.

How can I ensure that the function will only be run once every time?

Source: AngularJS Questions

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.