javascript - Angular 检测离开路线。

标签 javascript angularjs angular-ui-router

我正在使用 Angular 1.5 和 ui-router。我想检测用户何时离开路线。我目前有类似的东西:

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

这不太有效,因为当用户导航到此路由时,$scope.flag 设置为 false 并且此函数错误地触发。当用户导航离开特定路线而不是导航到该路线时,是否有一种惯用的方法来触发函数?

最佳答案

我会说使用 onExit您可以在单一状态下指定的 ui-router 钩子(Hook)。但您无法访问其中的 $scope

为了解决这个问题,我会说维护具有可共享数据的服务。从 onExit Hook 更改所需状态的可共享数据。然后您也可以在 Controller 内访问相同的服务。

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

关于javascript - Angular 检测离开路线。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39027921/

相关文章:

javascript - Angular 限制对 View 的访问,除非有 cookie

javascript - 将从 JSON 读取的多段落文本渲染到 React 组件中的最佳方法

angularjs - 带有OR语句的AngularJS ng-repeat过滤

javascript - 使用 JavaScript 过滤标签的搜索属性

javascript - AngularJS 输入类型 = 监视变化的数字的指令

javascript - 在 Angular js中获取index.php内容

javascript - 当 Angular Service 将动态 URL 作为常量时,如何处理?

angularjs - 如何检查ui-router中的当前状态是否是抽象状态的子级

javascript - 我怎样才能让我的数组成为 JavaScript 中*漂亮*人类可读的列表?

javascript - div 中的 Google 新闻框