问题
I need to fire an event whenever the user navigates forwards or backwards through their browser history, but only while on a particular route. I've tried using $scope.$on('$locationChangeSuccess', function...
within the controller for this route, but this will fire even if I'm navigating to a completely different route using the browsers forward and backward buttons.
I was able to prevent this behavior when navigating forwards through the browser history by checking $location.path()
and only executing the code if it matched the route. Unfortunately, this doesn't work if navigating backwards through the browser's history to a different route. I've added some excerpts from the code below to clarify.
// How parameters are being updated
$location.search('folder', searchId);
// Listening for the change
$scope.$on('$locationChangeSuccess', function() {
if ($location.path() === '/initialRoute') {
doThings();
}
});
When this code fails as I navigate back in my browser history to a different route, I end up stuck on the original route and the URL becomes website.com/initialRoute?optional_params=
, which it should never be, rather than website.com/routeInMyHistory
.
Recap: Works going forwards in browser history, but not back.
来源:https://stackoverflow.com/questions/36561895/how-to-fire-function-after-parameter-change-but-not-when-navigating-to-a-new-ro