gpt4 book ai didi

angularjs - 位置发生变化时如何获取路线名称?

转载 作者:行者123 更新时间:2023-12-02 19:11:38 25 4
gpt4 key购买 nike

我定义了一些路线:

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

最佳答案

您可以注入(inject) $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方法。

更新

如果您想拥有当前路由参数的数组,只需像上面那样注入(inject) $routeParams 服务即可。

关于angularjs - 位置发生变化时如何获取路线名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15354329/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com