Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Refresh (F5) and get another page with AngularJS?

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.

like image 697
Guy Ben-Moshe Avatar asked Dec 14 '15 12:12

Guy Ben-Moshe


Video Answer


2 Answers

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.

like image 110
Sudhansu Choudhary Avatar answered Oct 30 '22 19:10

Sudhansu Choudhary


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.

like image 23
Shashank Agrawal Avatar answered Oct 30 '22 20:10

Shashank Agrawal