iJade
iJade

Reputation: 23811

How to redirect in angularjs

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.

Upvotes: 2

Views: 9892

Answers (3)

Arshabh Agarwal
Arshabh Agarwal

Reputation: 556

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)

Upvotes: 6

Ryan Kinal
Ryan Kinal

Reputation: 17732

window.location = 'myURL'

Here's the MDN docs

Upvotes: -4

Joseph Silber
Joseph Silber

Reputation: 220056

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();
    }
});

Upvotes: 7

Related Questions