Search code examples
javascriptangularjsback-buttonangular-routing

Angular $location not updating when browser back is used


Has anyone run across this behaviour? There isn't much mentioned about it, and the other posts are different in nature. This appears to be inconsistent w/ documentation about browser behaviour.

Synchronizes the URL with the browser when the user

  • Changes the address bar.
  • Clicks the back or forward button (or clicks a History link).
  • Clicks on a link.

https://docs.angularjs.org/api/ng/service/$location#!

What happens:

This is a watcher to on location to help debug:

// listen for the event in the relevant $scope
$rootScope.$on('locationChange', function (event, data) {
    console.log(data);
});

//Call locationChange watch at anytime the page is loaded 
$scope.$emit('locationChange', $location.$$path);

Here's the routing:

$routeProvider
    .when('/guide', {
        templateUrl: 'views/guide.html',
        controller: 'GuideController',
        controllerAs: 'guide'
    })
    .when('/', {
        templateUrl: 'views/about.html',
        controller: 'AboutCtrl',
        controllerAs: 'about'
    })
    .otherwise({
        redirectTo: '/'
    });

Solution

  • How I solved this:

    var pop = 0;
    
    window.onpopstate = function(event) {
        if (document.location.pathname === '/' && pop > 1) {
            pop = 0;
            document.location = 'http://localhost:9000/';
        }
        pop++;
    };