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
  • 452
  • 8
  • 24

4 Answers4

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,678
  • 1
  • 7
  • 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
  • 102,126
  • 13
  • 159
  • 155
-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 Beck
  • 2,392
  • 1
  • 11
  • 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
-1

I think this question has already been answered...

assuming you are using Angular1, I think that the answer can be found here

and

assuming you are using Angular2, I think that the answer can be found here

jtbaird
  • 1
  • 3