Search code examples
javascriptangularjskeyboardbackspace

AngularJS way to disable a key


In my AngularJs project I want to disable the backspace key for all views. Here is an easy jQuery solution. Is there any solution for this written in AngularJs?

$(document).on("keydown", function (e) {
    if (e.which === 8 && !$(e.target).is("input, textarea")) {
        e.preventDefault();
    }
});

Regards


Solution

  • If you want to disable the backspace key for the entire website you can use something similar to this (Angularjs : disable tab key default behaviour) and apply the directive to the body document using the $document.

    Something like this:

    angular.module('app', []).directive('muteKey', ['$document', function($document) {
      return function(scope, element, attrs) {
        $document.on("keydown", function(e) {
         /*
          * you don't need the $(e.target) if you want to
          * disable the key press in any place of the project
          * and not just for inputs or textareas
          */
          if (e.which === 8) {
            e.preventDefault();
          }
        });
      };
    }]);
    
    <body mute-key>
        <!---->
    </body>