AngularJS $ location replace () replaces the latest history record as well

In my AngularJS application, I only need to save state changes in the browser history. Therefore, when I change the parameters of $ location, I use the replace () method.

For example, when I refer to / page 1, this is stored in the history. The center parameter is added automatically with replacement (), so it does not add a new history record:

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

Each time I move the map, the "center" changes.

When I go to / page 2, a new history entry is created. When I move the map, the "center" changes.

The fact is that when I press the BACK button, I am going to / page 1, but I need to maintain the "center" as before, but it changes to what was saved along with the history record / page 1.

How can I fix this problem?

I tried to add:

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

After replacing (), but does not work.

+4
source share
3 answers

I found a search call and replaced it with a 0 ms timeout so that it would occur in a separate digest cycle from the main state change and prevent the previous state from being replaced.

Sort of:

$timeout(function() {
    $location.search('centre', hash).replace();
}, 0);
+2
source

This is how I solved it.

First, we need to save the search result as the previous and current:

$rootScope.$on('$locationChangeStart', function (event, toURL, fromURL) {
    if ($rootScope.search.current) {
        $rootScope.search.previous = $rootScope.search.current;
    }

    $rootScope.search.current = $location.search();
});

Then we need to always change the actual location in which we are at the moment.

$rootScope.$on('$locationChangeSuccess', function (event, toURL, fromURL) {
    $rootScope.actualLocation = $location.path();
});

And if the "Back Forward" button was clicked, the center should be changed in the URL (using previous search results) without clicking on a new history entry.

$rootScope.$watch(function () { return $location.path() }, function (newLocation, oldLocation) {
    if ($rootScope.actualLocation === newLocation) {
        $location.search('center', $rootScope.search.previous.center).replace();
    }
});
0
source

, api, :

window.history.replaceState(hash, null, $location.absUrl());
-2

All Articles