2

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

3 Answers 3

4

You can add an ng-keydown attribute to your <input> tag:

<input type="text" ng-keydown="checkKey($event)"/>

$scope.checkKey(keyEvent) {
    if (keyEvent.which === 13) { 
        $event.preventDefault();
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, But I want to disable the key for the entire window
1

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>

Comments

1

Use the $document Service

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

The $document service has methods which are a subset of jQuery called jqLite.


How can apply this code? My starting app is like angular.module("my_app", ['ngRoute']);

Put it in a run block:

angular.module("my_app").run(function($document) {

    $document.on("keydown", function keydown Handler(e) {
        //Put handler code here
    });

});

!$(e.target).is("input, textarea")

Can be translated:

(e.target.type == "input") || (e.target.type == "textarea");

1 Comment

How can apply this code? My starting app is like angular.module("my_app", ['ngRoute']);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.