Reputation: 566
I am trying to use angularJS UI routing. I have three webpages, clients can access the first page through some link but if the url has a token attached to it I am doing a $state.go('second-page') in the controller. If the token is null I keep the client on the first page. However I want that when the client presses the back button on the browser the client should go to the first page. Which does not happen.
So the scenario is
client comes through the link
'#/form/calendar/:officeId/:token'
and since the token is not null I transition to the second page which does not have a URL the URL now becomes
'#/form/'
but when the client presses the back button it tries to go to
'#/form/calendar/:officeId/:token'
which results in a cyclic transition to the second page and the client can never reach the first page.
Please advise on how to avoid this.
Thank You
Upvotes: 0
Views: 125
Reputation: 61
You could perform your redirect from #/form/calendar/:officeId/:token
to #/form/
using the replace method of the $location
service. This will replace the current browser history entry with the new page, instead of adding a new one.
AngularJS description of the replace function:
replace() - If called, all changes to $location during current $digest will be replacing current history record, instead of adding new one.
You would perform the redirect like this:
$location.path('/form').replace();
Upvotes: 1
Reputation: 4623
There's nothing in the router that's really designed for this, but it's fairly easy to implement yourself. The router posts a $stateChangeStart
event that you can listen to. On the second trigger you would simply want to inhibit this redirect. Or simply DO the redirect in there, one time:
var redirected = false;
$rootScope.$on('$stateChangeStart', function(e, to, toParams, from, fromParams) {
// Redirect the user but only once
if (!redirected && toState.whateverYouWantToCheck) {
e.preventDefault();
redirected = true;
$state.go(...);
}
});
This will allow you to perform the redirect but only one time.
Upvotes: 1