I have a search page that allows the user to drill-down into categories and/or enter search terms. I want to give the user the ability to use the back button to undo these actions. Using AngularJS, how can I have this page add entries to the browsers history for each of these actions. I cannot use HTML5 pushstate.
4 Answers
I found I can do this by changing the query string parameters without reloading the page by using the answer about reloadOnSearch from here:
$routeProvider
.when('/items', {
controller: 'ItemsCtrl',
templateUrl: '/templates/items',
reloadOnSearch: false
},
...
);
And then, from that same answer, setting the query string using:
$location.search('id', 123);
And finally detecting route changes by using the answer from here:
$scope.$on('$routeUpdate', function(){
$scope.sort = $location.search().sort;
$scope.order = $location.search().order;
$scope.offset = $location.search().offset;
});
-
Exactly what I was looking for. Thanks! – LT86 Dec 02 '15 at 12:44
-
16 years later, still helpful! I needed to dynamically update the url params on a page based off user input. The refresh when using history pushstate was driving me bonkers. Thanks :) – Kyle Hawk May 25 '18 at 16:58
You can turn off the HTML5 mode with $locationProvider.html5Mode(false)
.
Then just use hashbang urls like <a href="#!/search">Search</a>
, they will be added to the history of the browser.

- 5,751
- 4
- 31
- 56
-
1Is it possible to change the route without having the controller get re-initialized? – adam0101 Sep 26 '13 at 16:12
I don't believe it's possible to add entries to the browser history without using HTML5 pushstate (at least, without actually changing the current location).
The MDN page discusses the introduction of pushstate and how it enables this new functionality (implying it wasn't possible before): https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history
EDIT: If the reason you can't use HTML5 pushstate is because of browser support, see this polyfill: https://github.com/browserstate/history.js

- 2,651
- 1
- 21
- 28
Along with the reloadOnSearch below code to track the location change event worked for me.
$scope.$on('$locationChangeSuccess', function () {
$scope.sort = $location.search().sort;
$scope.order = $location.search().order;
$scope.offset = $location.search().offset;
});
Though it might help for someone.

- 643
- 4
- 11