如何在位置变化时获取路线名称?

时间:2013-03-12 05:59:17

标签: angularjs

我定义了一些路线:

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

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

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,但不能获得路线名称。


更新

更复杂的用例:

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

如果当前路径是:

/users/12345

它应匹配/users/:id,但我如何知道哪条路线匹配并获取路线名称/users/:id

4 个答案:

答案 0 :(得分:62)

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

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

中找到其他有用的$ location方法

<强>更新

如果你想拥有一个当前路由参数的数组,只需像上面那样注入$ routeParams服务。

答案 1 :(得分:8)

您无需注入$location$routeParams 您可以使用current.$$route.originalPath

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

这对于简单路线(没有:id等)就足够了。

使用更复杂的用例,它将返回/users/:id 但您可以从:id中提取current.params.id参数,并在完整路线中替换它。

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);
    });
});

根据您对路线字符串的确切要求,与Flek的答案相比,这可能是混乱的(例如,如果您有多个参数),或者如果您不想被绑定到路线参数名称。

另请注意:您的代码中$on左大括号中缺少右括号。

修改15/01/2014

看起来Angular中的$$属性是私有的,我们不应该直接从我们的代码中调用它们。

答案 2 :(得分:2)

不是一个非常优雅的解决方案,我只在Chrome DevTools中进行了测试,但似乎有效:

Object.getPrototypeOf($route.current) === $route.routes['/users/:id];

对于想要使用此功能的其他人,只需将'/users/:id'替换为您在定义路线时使用的模式。

此外,如果您想匹配其他路径,请使用$route.routes['null']

免责声明:这只是我找到的解决方法,对我有用。鉴于此行为未记录,并且我没有对其进行测试以确定它是否适用于所有方案,因此使用它需要您自担风险。

答案 3 :(得分:0)

我认为您可以轻松地从true

获取路径
false