How to get the route name when location changes?

后端 未结 4 980
借酒劲吻你
借酒劲吻你 2020-12-05 13:35

I defined some routes:

angular.module(\'myApp\', [])
  .config(\'$routeProvider\', function($routeProvider) {
    $routeProvider.when(\'/aaa\', { templateUrl         


        
4条回答
  •  失恋的感觉
    2020-12-05 13:57

    You don't have to inject $location and $routeParams.
    You can use current.$$route.originalPath

    app.run(function ($rootScope) {
        $rootScope.$on('$routeChangeSuccess', function (e, current, pre) {
            console.log(current.$$route.originalPath);
        });
    });
    

    This is enough for simple routes (without :id, etc.).

    With the more complex use case, it will return /users/:id.
    But you can extract the :id param from current.params.id and replace it in the full route.

    app.run(function ($rootScope) {
        $rootScope.$on('$routeChangeSuccess', function (e, current, pre) {
            var fullRoute = current.$$route.originalPath,
                routeParams = current.params,
                resolvedRoute;
    
            console.log(fullRoute);
            console.log(routeParams);
    
            resolvedRoute = fullRoute.replace(/:id/, routeParams.id);
            console.log(resolvedRoute);
        });
    });
    

    Depending on exactly what you need do with the route string, this could be messy compared to Flek's answer (e.g. if you have several params), or if you don't want to be bound to the route params names.

    Also Note: There's a missing closing brace in your code for the $on opening brace.

    Edit 15/01/2014

    Looks like the $$ properties in Angular are suggested to be private and we should not call them directly from our code.

提交回复
热议问题