位置更改时如何获取路线名称? [英] How to get the route name when location changes?

查看:25
本文介绍了位置更改时如何获取路线名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了一些路由:

angular.module('myApp', [])
  .config('$routeProvider', function($routeProvider) {
    $routeProvider.when('/aaa', { templateUrl: '/111.html' })
                  .when('/bbb', { templateUrl: '/222.html'});
  });

我想在用户更改路线时获取路线名称:

And I want to get the route name when user changes the route:

angular.module('myApp')
  .run(['$rootScope', function($rootScope) {
    $rootScope.$on('$routeChangeSuccess', function(scope, current, pre) {
      // how to get current route name, e.g. /aaa or /bbb
      console.log('Current route name: ' + ???);
    }
  }]);

但我不知道如何获得它.我可以获取 templateUrl,但不能获取路由名称.

But I don't know how to get it. I can get the templateUrl, but not the route name.

更新

一个更复杂的用例:

$routeProvider.when('/users/:id', { templateUrl: '/show_user.html' })

如果当前路径是:

/users/12345

它应该匹配/users/:id,但是我怎么知道匹配哪个路由并获得路由名称/users/:id?

It should match /users/:id, but how do I know which route is matched and to get the route name /users/:id?

推荐答案

您可以注入 $location 服务并利用其 path() 函数.

You can inject the $location service and make use of its path() function.

angular.module('myApp')
  .run(['$rootScope','$location', '$routeParams', function($rootScope, $location, $routeParams) {
    $rootScope.$on('$routeChangeSuccess', function(e, current, pre) {
      console.log('Current route name: ' + $location.path());
      // Get all URL parameter
      console.log($routeParams);
    });
  }]);

您可以在 docs

更新

如果您想拥有当前路由参数的数组,只需像我上面所做的那样注入 $routeParams 服务.

If you want to have an array of your current route parameters, just inject the $routeParams service like I did above.

这篇关于位置更改时如何获取路线名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆