1

Coming from Django world, I'm just in love with it's cool feature about URL which prevent us to hardcode URLs in templates & views:

In urls.py:
url(r'/url/param1/param2/$', 'view_name', name="URL_NAME"),

In Template:
<a href="{% url "URL_NAME" @param1 &param2 ... %}">My link</a>

This way, if I want to change this URL I don't have to change it in my multiple files. I'm wondering if angular allow us to also do this. Now i have to write things like that:

In my App: 
when('/home', {
        templateUrl: 'app/home/home.tpl.html'
    }).

In my view:
<a href='#/home'>my link</a>

thanks for your help.

1 Answer 1

2

Here is a simple solution.

First, I added the name of the view in the $routeProvider configuration. For example we defined the name of the route '/login/:arg1/with/:arg2' to 'view_name':

myApp.config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/login/:arg1/with/:arg2', {
            templateUrl: 'app/common/login/login.tpl.html',
            name: 'my_view_name'
        }).

Then I created a directive to dynamically transform your view name to the correct url:

myApp.directive('viewUrl', function ($route) {
    return {
        restrict: 'A',
        link: function (scope, elem, attrs) {
            var splitArgs = attrs.viewUrl.split(' ');
            var view_name = splitArgs.shift();
            var url="route not found";
            for(var route in $route.routes){
                if ($route.routes[route].name == view_name){
                    url = route;
                }
            }
            for (var arg in splitArgs) {
                keyValue = splitArgs[arg].split(':');
                url = url.replace(":"+keyValue[0], keyValue[1]);
            }
            elem.prop('href', url);
        }
    }
});

Now you can use the view-url attribute in your html components like that:

<a view-url="my_view_name arg1:value1 arg2:value2">Hello World</a>

This will add the href element to your link and you will get this result:

<a view-url="my_view_name arg1:value1 arg2:value2" href="/login/value1/with/value2">Hello World</a>

Take care of the name of your arguments as I am using the replace function.

Sign up to request clarification or add additional context in comments.

1 Comment

Coming from django myself, the fact that this is not an Angular built-in is beyond me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.