Search code examples
angularjsangular-ui-router

Warn user before navigating to a different view


I would like to warn user and get a confirmation before the user navigates away from certain pages in my application, like composing a new message view. Which events can i capture and cancel/continue to make this happen ?


Solution

  • If you have say a link or button navigating to another route or state, you could simply show a modal confirming the navigation:

    <a href="" ng-click="goToAnotherState()">Go Away...</a>
    
    $scope.goToAnotherState = function(){
    
    //show modal and get confirmating however your like
      if(modalResponse.Ok){
         $state.go('anotherState');
      }
    }
    

    another option would be to do this in the $locationChangeStart event of ui-router, but if you're looking to this only here n there, then the first approach is better. $locationChangeStart approach:

    $rootScope.$on('$locationChangeStart', function (event, next, prev) {
      event.preventDefault();
      //show modal
      if(modalResponse.ok){
        var destination = next.substr(next.indexOf('#') + 1, next.length).trim();
        $location.path(destination)
      }
    }