Andrew Eisenberg
Andrew Eisenberg

Reputation: 28747

What is the equivalent of document.location.pathname in angular's $location?

There is a mismatch between document.location.pathname and $location.path().

I have an angular SPA running out of something like http://myhost.com/services/coolstuff.

When you navigate to that location, I have some router rules to navigate you to something like: http://myhost.com/services/coolstuff#/users/1.

At this point, you can call $location.path() and it will give you /users/1. And document.location.pathname gives you /services/coolstuff.

Is there a mechanism to retrieve the actual URL path from $location? I don't want the Angular hash path (/users/1), but the actual URL path (/services/coolstuff). How can I get that?

Upvotes: 1

Views: 1247

Answers (1)

Christoph
Christoph

Reputation: 51191

A bit late to the party here, but the parsing section of the URL specification is very specific about this (and super tedious to read...):

The gist of the above specification is, that an unencoded # character denoted the start of the URL fragment, which is not part of the path.

This essentially means, that $location.path() behaves differently from what the URL specification defines. An implementation compliant with the spec has to return /services/coolstuff as document.location.pathname consequently does.

In general, if something is supported in native JS, I would always opt for that, since you can be sure (as you see from your example) that browser implementations adhere to the specified standards which is often not the case for third party libraries.

Upvotes: 1

Related Questions