Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS $location replace() replacing last history entry also

On my AngularJS application I need to save only state changes in the browser history. That's why when I'm changing parameters of $location, I'm using replace() method.

For example, When I'm accessing /page1, it is save in the history. 'centre' parameter is added automatically with replace() so it doesn't add a new history entry:

$location.search('centre', hash).replace();

Every time I move a map, 'centre' changes.

When I go to /page2, the new entry in the history is created. When I move map, 'centre' changes.

The thing is that when I press BACK button, I'm going to /page1 but I need to keep 'centre' the same as it was before, but it changes to what was saved together with history entry of /page1.

How would I fix this issue?

I tried to add:

$window.history.replaceState({}, '', $location.absUrl());

After I do replace(), but didn't work.

like image 282
Julius Avatar asked Nov 22 '22 04:11

Julius


1 Answers

I found calling the search & replace inside a 0ms timeout ensures it happens in a separate digest cycle from the main state change and prevents the previous state being replaced.

Something like:

$timeout(function() {
    $location.search('centre', hash).replace();
}, 0);
like image 85
Justin Caldicott Avatar answered Nov 24 '22 17:11

Justin Caldicott