Reputation: 23811
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
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
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