I defined some routes:
angular.module(\'myApp\', [])
.config(\'$routeProvider\', function($routeProvider) {
$routeProvider.when(\'/aaa\', { templateUrl
You don't have to inject $location
and $routeParams
.
You can use current.$$route.originalPath
app.run(function ($rootScope) {
$rootScope.$on('$routeChangeSuccess', function (e, current, pre) {
console.log(current.$$route.originalPath);
});
});
This is enough for simple routes (without :id
, etc.).
With the more complex use case, it will return /users/:id
.
But you can extract the :id
param from current.params.id
and replace it in the full route.
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);
});
});
Depending on exactly what you need do with the route string, this could be messy compared to Flek's answer (e.g. if you have several params), or if you don't want to be bound to the route params names.
Also Note: There's a missing closing brace in your code for the $on
opening brace.
Edit 15/01/2014
Looks like the $$
properties in Angular are suggested to be private and we should not call them directly from our code.
Not a very elegant solution, and I have only tested it in Chrome DevTools, but it seems to work:
Object.getPrototypeOf($route.current) === $route.routes['/users/:id];
For others wanting to use this, just replace '/users/:id'
with the pattern that you used when you defined your route.
Also if you want to match the otherwise path, just use $route.routes['null']
Disclaimer: This is just a workaround that I found and which works for me. Given that this behavior is not documented, and that I didn't test it to see if it works in all scenarios, use it at your own risk.
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);
});
}]);
You can find other useful $location methods in the docs
UPDATE
If you want to have an array of your current route parameters, just inject the $routeParams service like I did above.
I think you can easily get the path from current
app.run(function ($rootScope) {
$rootScope.$on('$routeChangeSuccess', function (e, current, pre) {
console.log(current.originalPath); // Do not use $$route here it is private
});
});