user187676
user187676

Reputation:

Relative links in AngularJS

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)

Upvotes: 2

Views: 5927

Answers (4)

Ron Saylor
Ron Saylor

Reputation: 381

Old question, but I found this works:

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

Upvotes: 1

Yun Jia
Yun Jia

Reputation: 106

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

Upvotes: 2

McAden
McAden

Reputation: 13972

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.

Upvotes: 2

Langdon
Langdon

Reputation: 20053

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?

Upvotes: 1

Related Questions