Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent backspace from navigating back in AngularJS

I faced this issue in my AngularJS webapp.

When a user enters a page with a form to fill and he starts typing, if he presses the backspace key and the focus is not on the input text, then the page goes to the previous state.

I looked up this solution using jQuery, but it doesn't seem the appropiate way for achieve this in AngularJS.

like image 968
gyss Avatar asked Mar 12 '15 09:03

gyss


People also ask

How do I turn off backspace key?

Use the ALT+LEFT keyboard shortcut instead of Backspace. Set the browser. backspace_action to 0 in the about:config settings panel to re-enable support for the Backspace key as a Back button.


2 Answers

There is $document in angular js:

angular.module('yourModule', [])
  .controller('yourController', ['$scope', '$document', function($scope, $document) {
      $document.on('keydown', function(e){
          if(e.which === 8 && ( e.target.nodeName !== "INPUT" && e.target.nodeName !== "SELECT" ) ){ // you can add others here inside brackets.
              e.preventDefault();
          }
      });

    }
  ]);

Plnkr Demo.

You can see in the demo i have used only for "INPUT" nodeName and it does not prevent the default of the backspace key on text input but not on textarea because we have not handled it in the condition.

like image 183
Jai Avatar answered Sep 19 '22 02:09

Jai


I can't comment "accepted answer", but it will work not right, as condition

e.which === 8 && e.target.nodeName !== "INPUT" || e.target.nodeName !== "SELECT"

with logic error, so you can use

e.which === 8 && e.target.nodeName !== "INPUT" && e.target.nodeName !== "SELECT"

or answer that wrote @ThisIsMarkSantiago.

like image 26
Anatolii Chmykhalo Avatar answered Sep 20 '22 02:09

Anatolii Chmykhalo