我可能只是错过了一些简单的东西,但我想别名我的路由。我试图让路由/hello_world只是转发到/posttemplate的现有路由。我希望能够像这样为我的路由命名,以便用户轻松记住获取动态链接的方法…比如博客中的永久链接。还有,这是另一个问题,有没有人知道在angular中有什么好办法将所有这些路由定义在json或xml文件中,这样在添加很多路由时还能保持整洁?
application.config(['$routeProvider', '$locationProvider', function AppConfig($routeProvider, $locationProvider, $routeParams) {
$locationProvider.html5Mode(true).hashPrefix('!');
$routeProvider.when("/dashboard", {
controller: 'controllers.DashboardController',
templateUrl: 'templates/dashboard.html'
}).when("/wishlist", {
controller: 'controllers.WishlistController',
templateUrl: 'templates/wishlist.html'
}).when("/login", {
controller: 'controllers.LoginController',
templateUrl: 'templates/login.html'
}).when("/posttemplate", {
controller: 'controllers.PostTemplateController',
templateUrl: 'templates/posttemplate.html'
}).when("/hello_world", {
controller: 'DynamicRouteController',
templateUrl: function(params){ return '/posttemplate?id=1' }
}).otherwise({
controller: 'controllers.HomeController',
templateUrl: 'templates/home.html'
});
}]);
我认为你应该首先仔细规划你的URL模式。把/{{post_name}}
和/posttemplate
放在同一水平上似乎不是个好主意。
也许你可以试着给你所有的文章添加一个路径前缀,比如/post/:post_name
。然后你可以把这个添加到你的路由器配置中:
.when("/post/:post_name", {
controller: 'DynamicRouteController',
templateUrl: 'templates/posttemplate.html'
}
然后在DynamicRouteController
中,从$routeParams
读取post_name
并将其映射到您的帖子id。您可以在您的帖子中添加unique_name
字段,其中存储您想要访问的URL (/post/post_name)。
或者,如果你真的想,你也可以把它们放在同一个级别。只要确保"catch-all"条目位于路由器配置的末尾。
如果你愿意,你也可以把路由器的配置保存到一个JSON文件中。只需迭代配置项数组并将它们传递给when()
。
您可以使用redirectTo
从"别名"重定向到其他路由。
.when("/hello_world", {
redirectTo: '/posttemplate'
}
查看$routeProvider的文档获取更多信息
嗯…这是我最后做的…如果有人知道更好的方法…让我知道。
routes["/dashboard"] = {
controller: 'controllers.DashboardController',
templateUrl: 'templates/dashboard.html',
aliases: ['/dash','/dasher'],
meta: {
title: "Dashboard",
description: 'This is my description'
}
};
routes["/bucket"] = {
controller: 'controllers.PostTemplateController',
templateUrl: 'templates/posttemplate.html',
aliases: [],
arguments: {
id: 1
},
meta: {
title: "Dashboard",
description: 'This is my description'
}
};
//Incontroller
if (!postId)
postId = $route.current.arguments.id;
查看这个项目ui-router。它提供了几个特性来增强你的路由和模板管理。