2

In my templates I want to use relative routes. Currently I have absolute paths in my anchor href's, which is suboptimal

<a href="/#/dashboard/settings">Settings</a>

How can I rewrite this to be a relative navigation (in this relative to dashboard)?

It should work with hashbang and html5 history api routes (whichever AngularJS uses or falls back to)

4 Answers 4

2

Within your controller you can look at the $routeParams and build a base url to operate from.

From there your templates can operate against "{{baseUrl}}/relative/to/scope/baseUrl"

And urls built within your code can go to $scope.baseUrl + /relative/to/scope/baseUrl";

It's not exactly "relative" but it does solve the issue of allowing urls refining other urls without having to hard-code the hierarchy and worry about routeparams that are variables and such.

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

Comments

2

I'm not sure your angular version, but in my 1.2.18, when you set

<base href="/base"></base>

and whenever in your element href, you start with "relative/to/you/url", then your link will point to "/base/relative/to/you/url":

<a href="relative/to/you/url"></a>

NOTE: I've turned on the html5 api mode for $locationProvider:

$locationProvider.html5Mode(true);

EDIT: See MDN document for <base> tag. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base

Comments

1

I don't think you can rewrite it to use relative navigation. How is relative going to work if you want to link to /user/profile, but your user is on /dashboard/settings. If the main navigation links to simply profile (relative), it's going to go to /dashboard/profile, which I'm assuming is not what you want.

Why is relative pathing so important in your application? Anything more than savings keystrokes?

4 Comments

Is there at least a way to tell angular to automatically replace the /#/ prefix with / if HTML5 routing is available (or vice versa)?
Yes, if you use the $locationProvider with .html5Mode(true): docs.angularjs.org/guide/dev_guide.services.$location
I already use that, but it doesn't substitute the hash, just escapes it /#%2Fdashboard%2Fsettings.
Maybe you've misconfigured it? Here's a simple example: home.langdonx.com/location-test In Chrome, you'll see nice Urls, in IE9 you'll see hashbang.
1

Old question, but I found this works:

$locationProvider.html5Mode({
    enabled: true,
    requireBase: false,
    rewriteLinks: false
});

Comments

Your Answer

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