How to fire function after parameter change, but not when navigating to a new route

折月煮酒 提交于 2019-12-11 10:47:49

问题


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

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