angularjs – 当位置更改时如何获取路线名称?
发布时间:2020-12-17 08:26:40 所属栏目:安全 来源:网络整理
导读:我定义了一些路线: angular.module('myApp',[]) .config('$routeProvider',function($routeProvider) { $routeProvider.when('/aaa',{ templateUrl: '/111.html' }) .when('/bbb',{ templateUrl: '/222.html'}); }); 而当用户更改路由时,我想获取路由名称
我定义了一些路线:
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?
您可以注入$ location服务并使用其path()函数。
angular.module('myApp') .run(['$rootScope','$location','$routeParams',function($rootScope,$location,$routeParams) { $rootScope.$on('$routeChangeSuccess',function(e,pre) { console.log('Current route name: ' + $location.path()); // Get all URL parameter console.log($routeParams); }); }]); 您可以在docs中找到其他有用的$位置方法 更新 如果你想有一个你当前路由参数的数组,只需像上面那样注入$ routeParams服务。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |