In my web application, I got a form on 2 different pages, purchase1 and purchase2.
If a customer refreshes the page at purchase2, I want the location to be changed back to purchase1.
I haven't found a way to do so, I've tried to make a config like that:
.config(function($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.when('/purchase2', '/purchase1');
}
But obviously, that way I can never get to purchase2 page.
I need it to happen only on manual user Refresh.
Is there any way to do so? Some built-in Angular function that happens on Refresh?
Something like
$scope.onRefresh = function(){
   $location.path('/dashboard/purchase1');
}
Haven't found anything like it.
You can listen for beforeunload event. beforeunload event will be triggered when someone hits a F5 or refreshes the page anyhow. Do something like,
var windowElement = angular.element($window);
windowElement.on('beforeunload', function (event) {
    event.preventDefault();
    //below is the redirect part.
    $window.location.href = '/purchase1';
});
Put this code on purchase2 page.
Yes, you can do it.
Register a global listener for state change:
$scope.$on('$stateChangeStart', function(event, toState, toParams, fromState) {
    // If fromState is null that means it is a page refresh otherwise
    // The fromState will be the purchase1
    if (toState.name == 'purchase2' && !fromState) {
        $state.go('purchase1');
        event.preventDefault();
        return;
    }
});
By global, I mean register the above in such a controller whose scope is available throughout your application like a controller added to your body or html tag.
Also, I'm assuming the purchase1 & purchase2 are the name of your states for both the pages. If they are parameters to a common state you can alter the code above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With