【问题标题】:Opposite of $routeChangeSuccess in AngularJSAngularJS 中 $routeChangeSuccess 的对面
【发布时间】:2012-09-01 12:30:20
【问题描述】:

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

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

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

而我使用这个:

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

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

【问题讨论】:

    标签: angularjs routes angularjs-routing


    【解决方案1】:

    在路由更改之前会触发 $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 服务发出的其他事件。

    【讨论】:

    • 非常感谢!这正是我正在寻找的!
    • 谢谢。但第一个参数实际上是事件。
    猜你喜欢
    • 2014-09-16
    • 2015-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-24
    • 1970-01-01
    • 2013-12-30
    相关资源
    最近更新 更多