Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - get the list of defined routes - $routeProvider

I am trying to implement named routes, so I don't have to write the whole path (often changes).

I was thinking I could get away with writing a service that would return the list of defined routes and a filter that would transform object to aroute

The use example would look like:

<a ng-href="{id:1}|route:'detail'">Click here!</a>

Provided I have added name:'detail' to my route definition, this would generate the following result :

<a href="#/detail/1/">Click here!</a>

I think this is quite simple, but:

How can I get the list of defined routes ?

I was thinking I can make use of routeProvider , but AFAIK it has no public methods or attributes I can access.

like image 964
g00fy Avatar asked Apr 15 '13 09:04

g00fy


1 Answers

turns out this is pretty straight forward:

http://plunker.co/edit/GNZxcvK4hfQ9LrlSvasK?p=preview

Components.filter('url', function ($route) {
  function resolveRoute(options, route) {
    var parts = route.split('/');
    for (var i = 0; i < parts.length; i++) {
      var part = parts[i];
      if (part[0] === ':') {
        parts[i] = options[part.replace(':', '')];
        if (parts[i] == undefined) throw Error('Attribute \'' + part + '\' was not given for route \'' + route + '\'')
      }
    }
    return parts.join('/');
  }

  return function (options, routeName) {
    var routes = [];


    angular.forEach($route.routes,function (config,route) {
      if(config.name===routeName){
        routes.push(route);
      }
    });

    if (routes.length == 1) {
      return resolveRoute(options, routes[0]);
    }
    else if (routes.length == 0) {
      throw Error('Route ' + routeName + ' not found');
    }
    throw Error('Multiple routes matching ' + routeName + ' were found');
  }
});
like image 78
g00fy Avatar answered Nov 15 '22 22:11

g00fy