knorv
knorv

Reputation: 50117

Is this the correct way to set up an onkeypress listener in AngularJS?

I want to setup an onkeypress listener in an AngularJS application to be able to catch all keypresses.

Questions:

This is the HTML code I'm using:

<html ng-app="moduleName">
  <body ng-controller="ControllerName" ng-keypress="keyPress($event)">
  </body>
</html>

And this is the JavaScript code:

var app = angular.module("moduleName", []);
var ControllerName = function($scope) {
    $scope.keyPress = function($event) {
        // Logic goes here.
    };
};

Upvotes: 2

Views: 191

Answers (1)

Anand
Anand

Reputation: 4551

Usually, Angular Application have multiple controllers, hence, you may want to:-

  1. Set keyPress method to rootscope on app initialization (as it seems you want this method to get called from keypress anywhere in application.

    app.config(['$routeProvider', '$rootScope',
      function ($routeProvider, $rootScope) {
        $routeProvider.when('/Sample', {
            templateUrl: 'views/Sample.html',
            controller: 'sampleController'
        });
    
        $routeProvider.otherwise({ redirectTo: '/app' });
        $rootScope.keypress = function($event) {
            /* some code goes here */
        };
    }]);
    
  2. You can also use directive for same purpose, which look like more appropriate way of handling this

    app.directive('listenToKeypress', function() {
       return {
         restrict: 'A',
         link: function(scope, elem, attr, ctrl) {
                 elem.bind('keypress', function(e) {
                     /* do something here */
                 });
         }
       };
    });
    

and html can be :-

<html ng-app="moduleName">
  <body ng-controller="ControllerName" listen-to-keypress>
  </body>
</html>

Upvotes: 1

Related Questions