AngularJS - 获取定义的路由列表 - $ routeProvider [英] 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).
我想我可以逃脱写作,将变换对象aroute服务,将返回定义的路由列表和过滤器
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
使用示例如下:
<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:
我怎样才能得到定义的路由列表?
我想我可以使用 routeProvider
,但据我所知它没有公共方法或属性,我可以访问。
I was thinking I can make use of routeProvider
, but AFAIK it has no public methods or attributes I can access.
推荐答案
原来,这是pretty直截了当:
turns out this is pretty straight forward:
<一个href=\"http://plunker.co/edit/GNZxcvK4hfQ9LrlSvasK?p=$p$pview\">http://plunker.co/edit/GNZxcvK4hfQ9LrlSvasK?p=$p$pview
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');
}
});
这篇关于AngularJS - 获取定义的路由列表 - $ routeProvider的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!