Change location of browser's back button in angular js

Issue

I have a wizard with multiple Steps. Let’s say something like this:

Product > Address > Payment > Verify

On the /verify step, the user buys something. If the user now presses the back button on the browser, he should go to the /product step and not to the /payment step. To do so, I want to change the browser history from /payment to /product so that he can buy more stuff.

I use angularjs 1.3.14 with enabled HTML5 mode and ui-router 0.2.10. So the solution might use HTML5 history. but it would be nice if it also works for older browsers. But the support is nice to have.

Solution

The answer from stackg91 gives me the right idea. As I don’t want to change the page to rechange it in the next moment, I listen on $stateChangeStart. So I’ve done something like this (pseudocode)

 obj.finishedStateListener = $rootScope.$on('$stateChangeStart', function (event, toState) {
     if(statechange inside wizard) {
         event.preventDefault();
         obj.finishedStateListener();
         $state.go(initState);
     }
 })

It is very important to save the return of the $on function, as it gives you the possiblility to unregister the eventListener. If you forget to call it, you will end in an infinite loop.

Answered By – waXve

Answer Checked By – Mildred Charles (AngularFixing Admin)

Leave a Reply

Your email address will not be published.