Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if a user clicks browser back button in Angularjs

Tags:

I have a form-like page with some data. And want to show a popup/alert when a user clicks the browser back button, asking "if they want to go back or stay on the same page". I am using angular-ui-router's $stateProvider and want to bind this only to one state/view.

like image 757
linyuanxie Avatar asked Apr 27 '15 16:04

linyuanxie


People also ask

How to detect browser back button event in AngularJs?

angular . module('app') . run(function($rootScope, $transitions) { // Track "previous state" to be used elsewhere to determine if the user // goes "back".

How does AngularJs detect browser?

$inject = ['$window']; function detectFactory($window) { return detect. parse($window. navigator. userAgent); } angular.

What is $$ in AngularJs?

The $ in AngularJs is a built-in object.It contains application data and methods.


1 Answers

This is my previous answer for some other question, but it should be good to help you

You can do it by using angular $routeChangeStart

$routeChangeStart

Broadcasted before a route change. At this point the route services start resolving all of the dependencies needed for the route change to occur. Typically this involves fetching the view template as well as any dependencies defined in resolve route property. Once all of the dependencies are resolved $routeChangeSuccess is fired.

The route change (and the $location change that triggered it) can be prevented by calling preventDefault method of the event. See $rootScope.Scope for more details about event object.


So please try this below code.

  $scope.$on('$routeChangeStart', function (scope, next, current) {
        if (next.$$route.controller != "Your Controller Name") {
            // Show here for your model, and do what you need**
            $("#yourModel").show();
        }
    });

Update:

You need to write your functional work in the model popup. like

Put some link buttons for

  • Are you sure for go to prev page?
  • do you want stay current page?
  • Do you want logout? etc.

then Add ng-click event for go prev page, stay current page with using return false, etc.

like image 113
Ramesh Rajendran Avatar answered Oct 17 '22 20:10

Ramesh Rajendran