Reputation: 135
I am new to angularjs but have been working with django for some time.
I am used to the idea of writing the following in my templates:
<a href="{% url 'profile-page' user.pk %}">{{ user.name }}</a>
and the following being generated in the rendered html:
<a href="/profiles/33">Eamonn</a>
n.b. this profile-page url is defined in my url routing
This is very powerful as I can change the urls without having to change the templates.
I am loving angularjs but I am not too happy adding my urls into my templates and I am using a name instead of the url which feels like I am programming to an interface and not an implementation. Also, if I specify a url two or three times in different templates it is not very DRY.
Is there any native way of doing this of something similar in angularjs?
Upvotes: 2
Views: 1463
Reputation: 28621
I've created a module to solve exactly this problem.
Here's the issue at AngularJS github: https://github.com/angular/angular.js/issues/7091#issuecomment-40742173
And here's the module repository: https://github.com/betsol/angular-router
This module works on top of this library: https://github.com/betsol/js-router
routerProvider
.when('/user/:userId/post/:postId/comment/add', {
name: 'user-post-comment-add',
templateUrl: '/partials/user-post-comment-add.html',
controller: 'UserPostCommentAddCtrl'
})
;
<a href="{{ router.generate('user-post-comment-add', { userId: 100, postId: 500 }) }}">Add comment</a>
Upvotes: 0
Reputation: 135
I found this library that does exactly what I want: https://github.com/airtonix/angular-named-routes
Thanks for your responses.
Upvotes: 0
Reputation: 19098
I would create a constant
in your app and then inject that into either the $rootScope
, or controller that looks after the specific part of the page with the links.
Something like this:
app.constant('appURL', {
login: '/login'
userProfilePrefix: '/profiles/'
});
Then your controller can request it as a dependency and put it on the scope (or you could put it on the $rootScope
in app.run(..)
:
app.controller('PageController', ['appURL', function($scope){
$scope.appURL = appURL;
$scope.userId = 33;
}]);
Finally, your HTML can use the following:
<a ng-href="{{appURL.userProfilePrefix + userId}}">Eamonn</a>
NOTE use ng-href where possible - all this does is means that if a user happens to click on a link before the interpolation has happened, they won't get redirected to /{{appURL.userProfilePrefix + userId}}
Upvotes: 1