William
William

Reputation: 502

How to get keypress if press a key anywhere in the document?

I am trying to fire keypress event anytime and anywhere I hit enter, but I only can reach this in specifying in a DOM element with ng-keypress.

I reached this result using pure javascript with this code:

document.onkeydown = function(e){
    if(e.keyCode === 13){
      //do something
    }
}

But I am not sure if this is the best way, or the "angular way" to do this.

Upvotes: 3

Views: 3768

Answers (3)

Matthew Cawley
Matthew Cawley

Reputation: 2818

To invoke a function on your nested controller...

You can use the built-in ng-keypress directive on the <body> tag:

<body ng-keypress="enterKeyPressed($event)">

That can be bound to a function on $rootScope from your module's run() block:

app.run(function($rootScope) {
  $rootScope.enterKeyPressed = function(e) {
    if (e.keyCode === 13) {
      $rootScope.$broadcast("EnterKeyPressed");
    }
  };
});

That raises an event that can be picked up using $scope from within your controller:

$scope.$on("EnterKeyPressed", function() {
  vm.incrementCounter();
});

Demo

CodePen: Using ng-keypress with an event

Upvotes: 2

tymeJV
tymeJV

Reputation: 104775

I'd wrap it in a directive and go from there, example:

angular.module("myApp").directive("keypressDetector", function() {
    return {
        restrict: "A",
        link: function(scope, elem, attrs) {
            document.onkeydown = function(e){
                if(e.keyCode === 13){
                    //do something
                }
            }
        }
    }
})

And use it:

<body keypress-detector></body>

Upvotes: 2

Ben
Ben

Reputation: 2706

If you're using AngularJS, you should ng-keydown on your outter-most HTML element.

For example:

<body ng-keydown="myKeyDownFunction($event)"></body>

$scope.myKeyDownFunction = function($event) {
    if($event.keycode === 13) {
         // Do what you need to do
    }
}

Upvotes: -1

Related Questions