如何创建一个AngularjJS“url_for”链接帮手 [英] How to create a 'url_for' link helper in AngularjJS
问题描述
在.NET MVC有 @ Url.Action()
和回报率有 url_for()
In .NET MVC there is @Url.Action()
and in RoR there is url_for()
我不能angularjs找到类似的URL建筑帮手。
I could not find similar url building helper in angularjs.
我已经提供了即构建URL以 $ routeProvider
所以像所需要的一切: $ routeProvider.urlFor(MyCtrl {ID:5})
可能是不错的。
I'm already providing everything that is needed to build url to $routeProvider
so something like: $routeProvider.urlFor("MyCtrl", {id: 5})
could be nice to have.
我这里主要目标是避免硬codeD网址viewes等地,并避免重复URL /路由模式的两倍。
My main goal here is to avoid hardcoded urls in viewes and other places and to avoid repeating url/routes patterns twice.
更新:
好像很难解释,我想所以这里是什么我想要什么确切的例子:
Seems like it's hard to explain what i want so here is exact example of what i want:
相反在viewes写这个的:
Instead of writing this in viewes:
<a ng-href="/product/5">foo</a>
我要这样写:
<a ng-href="urlFor("ProductCtrl", {id:5})">foo</a>
所以,如果以后我决定要改变ProductCtrl的道路,我不会在这一个元素来更新网址。
So if later i decide to change path of ProductCtrl I would not have to update url in this a element.
什么是良好的解决方案,我的目标?
What would be good solution for my goals?
推荐答案
您可以用类似下面的主模块的运行内(只是想出了它)尝试()块:
You could try with something like the following (just came up with it) inside your main module's run() block:
app.run(function($route, $rootScope)
{
$rootScope.path = function(controller, params)
{
// Iterate over all available routes
for(var path in $route.routes)
{
var pathController = $route.routes[path].controller;
if(pathController == controller) // Route found
{
var result = path;
// Construct the path with given parameters in it
for(var param in params)
{
result = result.replace(':' + param, params[param]);
}
return result;
}
}
// No such controller in route definitions
return undefined;
};
});
这将延伸与新的路径()功能的应用程序的根范围 - 因此它可以在任何地方在应用程序中使用。它使用$航线的得到控制的名称和相应的路径,这样你就不必重复自己。
This will extend the root scope of the application with the new path() function - so it can be used anywhere in the application. It uses the $route service to get the controller names and the corresponding paths, so you won't have to repeat yourself.
实例:
{{ path('LibraryController', { bookId : 'x', chapterId : 'y' }) }}
在活生生的例子:<一href=\"http://plnkr.co/edit/54DfhPK2ZDr9keCZFPhk?p=$p$pview\">http://plnkr.co/edit/54DfhPK2ZDr9keCZFPhk?p=$p$pview
这篇关于如何创建一个AngularjJS“url_for”链接帮手的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!