javascript - URL tag for angular -
coming django world, i'm in love it's cool feature url prevent 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 ¶m2 ... %}">my link</a>
this way, if want change url don't have change in multiple files. i'm wondering if angular allow this. have write things that:
in app: when('/home', { templateurl: 'app/home/home.tpl.html' }). in view: <a href='#/home'>my link</a>
thanks help.
here simple solution.
first, added name of view in $routeprovider configuration. example defined name of route '/login/:arg1/with/:arg2' '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 created directive dynamically transform view name 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; } } (var arg in splitargs) { keyvalue = splitargs[arg].split(':'); url = url.replace(":"+keyvalue[0], keyvalue[1]); } elem.prop('href', url); } } });
now can use view-url attribute in html components that:
<a view-url="my_view_name arg1:value1 arg2:value2">hello world</a>
this add href element link , result:
<a view-url="my_view_name arg1:value1 arg2:value2" href="/login/value1/with/value2">hello world</a>
take care of name of arguments using replace function.
Comments
Post a Comment