我正在使用 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/