Search code examples
angularjsroutesonbeforeunload

Angular: how to switch routes based on function calls


I have three routes in my app.js but when i am switching from create to any other route i want to check whether the user has intentionally click to switch or is it a mistake so there will be return popup that will ask user to stay on the page or leave the page. In usual cases it would have worked with this code:

window.onbeforeunload = confirmExit;
function confirmExit() {
    return "You have attempted to leave this page. Are you sure?";
}

but since this is a SPA application i have to run this function while switching the routes:

HERE IS MY ROUTES

testApp.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/tests', {
        templateUrl: 'partials/list.html',
        controller: 'ListCtrl'
      }).
      when('/tests/:testsId', {
        templateUrl: 'partials/detail.html',
        controller: 'DetailCtrl'
      }).
      when('/create/', {
        templateUrl: 'partials/create.html',
        controller: 'CreateCtrl'
      }).
      otherwise({
        redirectTo: '/tests'
      });
  }]);

any help is much appreciated.


Solution

  • I would to this with an angular directive :

    .directive('confirm', [
        function() {
            return {
                restrict: 'AEC',
                link: function($scope, element) {
                    element.bind('click', function(event) {
    
                            if (!confirm('You have attempted to leave this page. Are you sure?')) {
                                event.preventDefault();
                                return false;
                            }
                    });
                }
            };
        }
    ]);
    

    and in your HTML :

    <a href="/route" confirm>link</a>
    

    This way the standard link redirection will get intercepted and the redirection will only occur if user confirm it.

    Working fiddle : http://jsfiddle.net/HB7LU/3119/

    edit: removed jquery reference + jsfiddle link

    edit2: for global redirection interception (like a backspace key or any clicked link on the page), see this fiddle http://jsfiddle.net/9MnE9/124/

    Here, I use $routeChangeStart to watch any location change.