[Answered ]-URL tag for angular

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.

👤Julio

Leave a comment