Search code examples
angularjsangularjs-routing

Find route from angularjs routeprovider by name


I'm defining my routes like this.

$routeProvider
.when('/Home', {
     name: 'Main',
     templateUrl: 'Main.html',
     controller: 'MainController',
     controllerAs: 'ctrl'
})
.when('/About', {
     name: 'About',
     templateUrl: 'About.html',
     controller: 'AboutController',
     controllerAs: 'ctrl'
})

How can I in a controller find the '/About' URL by querying on the name 'About', when I'm in the Main controller?


Solution

  • Since there is nothing built in, an extending of route can solve this problem in a nice way:

    $provide.decorator('$route', ($delegate) => {
    
        $delegate.getRoute = (name) => {
            var result = null;
            angular.forEach($delegate.routes, (config, route) => {
                if (config.name === name) {
                    result = route;
                }
            });
            return result;
        };
    
        return $delegate;
    });