如何在AngularjJS中创建'url_for'链接帮助器

And*_*vko 12 url routing angularjs angularjs-routing

在.NET MVC中,存在@Url.Action()和在RoR中存在url_for()

我在angularjs中找不到类似的url building helper.

我已经提供了构建url所需的所有东西,$routeProvider所以:$routeProvider.urlFor("MyCtrl", {id: 5})可能很高兴.

我的主要目标是避免在视图和其他地方使用硬编码的网址,并避免重复网址/路由模式两次.

更新:

似乎很难解释我想要的东西,所以这里是我想要的确切示例:

而不是在视图中写这个:

<a ng-href="/product/5">foo</a>
Run Code Online (Sandbox Code Playgroud)

我想写这个:

<a ng-href="urlFor("ProductCtrl", {id:5})">foo</a>
Run Code Online (Sandbox Code Playgroud)

因此,如果以后我决定改变ProductCtrl的路径,我就不必在这个元素中更新url.

什么是我的目标的好方法?

mir*_*rmx 15

您可以在主模块的run()块中尝试使用以下内容(只是想出来):

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;
  };
});
Run Code Online (Sandbox Code Playgroud)

这将使用新的path()函数扩展应用程序的根范围 - 因此可以在应用程序的任何位置使用它.它使用$ route服务来获取控制器名称和相应的路径,因此您不必重复自己.

用法示例:

{{ path('LibraryController', { bookId : 'x', chapterId : 'y' }) }}
Run Code Online (Sandbox Code Playgroud)

实例:http://plnkr.co/edit/54DfhPK2ZDr9keCZFPhk?p =preview