Angular检测离开一个路由

Angular detect leaving a route.

本文关键字:一个 路由 检测 离开 Angular      更新时间:2023-09-26

我使用的是Angular 1.5和ui-router。我想检测用户leaves何时路由。我现在有这样的东西:

$scope.$on("$stateChangeSuccess", function () {
      if (!$scope.flag) {
        //...
        $scope.do_work(reason);
      }
    });

这并不能很好地工作,因为当用户导航到这条路由时,$scope.flag被设置为false,并且该功能不正确地触发。是否有一种习惯的方法可以在用户从某个特定的路径导航出去时触发函数,而不是在用户导航到该路径时?

我会说使用 onExit 钩子的ui-router,你可以指定一个状态。但是你不能访问$scope

要解决这个问题,我建议维护具有可共享数据的服务。更改所需状态的onExit钩子中的可共享数据。然后你也可以在你的控制器中访问相同的服务。

$stateProvider.state("contacts", {
  template: '<h1>Dummy Template</h1>',
  controller: 'myCotroller',
  onExit: function(sharableService){
    //... do something sharableService variable...
  }
})