如何获得路由名称时位置的变化? [英] How to get the route name when location changes?
本文介绍了如何获得路由名称时位置的变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我定义了一些路线:
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
,而不是路由名称。
更新
一个更复杂的用例:
$routeProvider.when('/users/:id', { templateUrl: '/show_user.html' })
如果当前的路径是:
/users/12345
它应与 /用户/:ID
,但我怎么知道哪个路线相匹配,并获取路线名称 /用户/: ID
?
It should match /users/:id
, but how do I know which route is matched and to get the route name /users/:id
?
推荐答案
您可以注入$位置服务,并利用其路径()函数。
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);
});
}]);
您可以在其他有用的$ location方法文档
You can find other useful $location methods in the docs
更新
如果你想拥有你当前的路由参数数组,只需注入$ routeParams服务像我上面那样。
If you want to have an array of your current route parameters, just inject the $routeParams service like I did above.
这篇关于如何获得路由名称时位置的变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文