3

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.

William
  • 502
  • 1
  • 9
  • 27

3 Answers3

2

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

Matthew Cawley
  • 2,688
  • 1
  • 8
  • 19
2

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>
tymeJV
  • 103,943
  • 14
  • 161
  • 157
-1

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
    }
}
Ben
  • 2,441
  • 1
  • 12
  • 16
  • 2
    My controller is inside the body tag, and when I put it inside the first
    in controller, it doesn't works.
    – William Sep 20 '17 at 18:55