9

我只是想知道是否有办法知道是否有人正在更改 URL 的路由。

例如,我的 html 中有这样的内容:

<a ng-href="#/somewhere">To somewhere</a>

正在使用这个:

$scope.$on('$routeChangeSuccess', function (scope, next, current) {
    //Some code
})

但是,我刚刚意识到我需要在更改 URL 之前运行此代码。有没有办法做到这一点,也有同样的方法next,并current知道我将被重定向到哪里以及从哪里?

4

1 回答 1

24

$routeChangeStart路线更改之前会触发事件。它支持 next 和 current 参数,就像您期望的那样。因此,为了涵盖您的用例,您可以编写:

$scope.$on('$routeChangeStart', function(scope, next, current){
        console.log('Changing from '+angular.toJson(current)+' to '+angular.toJson(next));
});

这是完整的 jsFiddle 说明了这一点:http: //jsfiddle.net/pkozlowski_opensource/9MnE9/

您可能还想查看 $route 文档 ( https://docs.angularjs.org/api/ngRoute/service/$route ) 以查看 $route 服务发出的其他事件。

于 2012-09-07T17:38:25.437 回答