问题
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