AngularJS redirect without pushing a history state

kyleder picture kyleder · Sep 25, 2013 · Viewed 17.4k times · Source

I'm working on an AngularJS app that has a catch all route (eg, .when('/:slug', {...)) which is necessary to support legacy url formats from a previous (non-angular) version of the app. The controller that responds to the catch all tries pulling a related object, and, if not found, redirects to a 404 page using the $location.path method. This works at getting the user to the 404 page, but when the user hits back in their browser it takes them back to the page that forced them to the 404 page in the first place and they end up being unable to escape the cycle.

My question is if there is 1) a better pattern for handling this situation, or 2) if there is a way to reroute the user that doesn't force a history push state in the browser?

Answer

thrashr888 picture thrashr888 · Sep 26, 2013

You can change the url without adding to the history state, found here under "Replace Method". This is effectively the same as calling HTML5's history.replaceState().

$location.path('/someNewPath').replace();

I haven't found that it's possible to change the view without changing the url. The only method to change the view, that I've found, is to change the location path.