Angular $location not updating when browser back is used

半世苍凉 提交于 2019-12-02 11:04:51

问题


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:

  • Load page - hash updates (http://localhost:9000/#/)
  • Click 'Start' - update $location.$$path via function to update hash and load new view (http://localhost:9000/#/guide)
  • Tricky! User clicks back-button in browser, hash updates back to http://localhost:9000/#/ but debug tells me $location.$$path still thinks we are at $location.$$path = /guide - logic based on location path doesn't work.

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: '/'
    });

回答1:


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++;
};


来源:https://stackoverflow.com/questions/34800757/angular-location-not-updating-when-browser-back-is-used

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!