2

This might be a trivial thing to do, but i'm a angularjs newbie. Here is my angularjs controller code

    function MyCtrl1($scope, $location, $rootScope) {
  $scope.$on('$locationChangeStart', function (event, next, current) {
    event.preventDefault();
    var answer = confirm("Are you sure you want to leave this page?");
    if (answer) {

    }
  });
}
MyCtrl1.$inject = ['$scope', '$location', '$rootScope'];

In the next variable i have the url to redirect on confirm OK.But how to accomplish this thing in angularjs.

3 Answers 3

7

You don't have to manually do it. Only cancel the event if they don't confirm:

$scope.$on('$locationChangeStart', function (event, next, current) {
    if ( ! confirm("Are you sure you want to leave this page?") ) {
        event.preventDefault();
    }
});
Sign up to request clarification or add additional context in comments.

Comments

6

You can use either plain javascript as mentioned in other answers or you can use $location service provided by angular like this

    $location.path(next)

OR

   $location.replace(next)

First one adds to your current path (mostly a partial)

Second one replaces current path (like google.com to yahoo.com)

Comments

-4

window.location = 'myURL'

Here's the MDN docs

1 Comment

using "window" is bad practice for Angular.js. Please always use $window instead. See docs.angularjs.org/api/ng.$window

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.