Search code examples
angularjsangularjs-routing

AngularJs get route by URL


Is there a way to get route by URL??

What I mean is I have a route /users/:id, I am getting route object using $route

var route_object = ($route.routes['/users/:id']);

But is it possible to get route with this URL /users/5

So when I try

var route_object = ($route.routes['/users/5']);

I am getting undefined value.


Solution

  • No, there is no build-in way to get a route object by corresponding url. However it's pretty easy to do with few lines of code. The idea is to test url against routes regular expressions:

    var url = '/users/5/';
    
    for (var path in $route.routes) {
        if ($route.routes[path].regexp && $route.routes[path].regexp.test(url)) {
            console.log('found route:', $route.routes[path]); 
        }
    }
    

    You can wrap it in helper function and put in in some util service maybe or controller:

    function getRouteByUrl(url) {
        for (var path in $route.routes) {
            if ($route.routes[path].regexp && $route.routes[path].regexp.test(url)) {
                return $route.routes[path]; 
            }
        }
        return null;
    }