Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overwrite $location pushState history AngularJS

If I am a returning user to a "results page" I want to see the last filters I used. So I am using ngCookies to update the last used search parameters on a page.

controller('Results', ['$location','$cookies',function($location,$cookies){
    $location.search(angular.fromJson($cookies.search));
}]);

//will yield: /results?param1=dude&param2=bro

However, if I click "back" I will not be brought to the last page I would expect.

That's because another state was pushed onto the history but was unperceived by the user.

The user landed on /results but the controller immediately pushed /results?param1=dude&param2=bro onto the state history.

How do I overwrite or delete the state /results so that "back" would return me to what a user would expect the last page they came from to be?

like image 995
Dan Kanze Avatar asked Jul 25 '13 13:07

Dan Kanze


1 Answers

Chain replace() onto the end of your $location.search call:

controller('Results', ['$location','$cookies',function($location,$cookies){
    $location.search(angular.fromJson($cookies.search)).replace();
}]);

This causes the last history entry to be replaced, rather than a new one added.

There is also the reloadOnSearch option which you can set to false to prevent reloading a route when the search params change (if you want the back button to go to /results).

like image 97
DanS Avatar answered Oct 05 '22 10:10

DanS