How to create a 'url_for' link helper in AngularjJS

angularjs, angularjs-routing, routes, url

Solution

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.

Example usage:

{{ path('LibraryController', { bookId : 'x', chapterId : 'y' }) }}

Live example at: http://plnkr.co/edit/54DfhPK2ZDr9keCZFPhk?p=preview

Problem

In .NET MVC there is `@Url.Action()` and in RoR there is `url_for()` I could not find similar url building helper in angularjs. 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. My main goal here is to avoid hardcoded urls in viewes and other places and to avoid repeating url/routes patterns twice. UPDATE: Seems like it's hard to explain what i want so here is exact example of what i want: Instead of writing this in viewes: ``` <a ng-href="/product/5">foo</a> ``` I want to write this: ``` <a ng-href="urlFor("ProductCtrl", {id:5})">foo</a> ``` 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?

Original source