21

I want to get the base path of my Angular app.

Right now I'm doing this: $scope.baseUrl = '$location.host()

But I only get this: /localhost. My current baseURL is http://localhost:9000/.

4
  • You also need $location.port() Commented Jan 30, 2016 at 2:03
  • absUrl() probably ? Check: docs.angularjs.org/api/ng/service/$location Commented Jan 30, 2016 at 2:04
  • 4
    $scope.baseUrl = $location.protocol() + "://" + location.host; Commented Jan 30, 2016 at 2:14
  • this question was really useful for me today. Yay :) Commented May 12, 2019 at 23:41

8 Answers 8

17

An alternative answer is using the $window service in conjunction with $location.absUrl() to create a new URL object, and then grab the origin via the origin property. This will give you exactly what you're looking for (minus the trailing '/').

$scope.baseUrl = new $window.URL($location.absUrl()).origin; will give you back http://localhost:9000 in your case.

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

Comments

15

Try this: $location.$$absUrl

console.log('$location',$location.$$absUrl);

btw /localhost is your base path, but I guess you meant entire URL.

1 Comment

You should not be using properties & functions that begin with $$ instead find a supported angular way of doing it. E.g. using the absUrl() method
10

To get just the baseurl and nothing else use

$browser.baseHref()

it will return something like

/central/

2 Comments

upvoted but this is private API and I prefer the result as someweb/somepath
This should be the accepted answer, $location doesn't provide what the OP wanted.
4

A cross browser solution that worked for me was:

$location.$$absUrl.replace($location.$$url, '')

$$absUrl is the entire url (e.g. https://google.com/search/spiders)

$$url is the part after the host (e.g. /search/spiders)

Modify to taste.

Comments

3

try injecting $location it has an absUrl() method on it that will return the entire current url

https://docs.angularjs.org/api/ng/service/$location

Comments

2

If you only want to get the base url of the site, and not the current url of the page, e.g. from https://www.google.com/somewhere/in-the-middle-of-nowhere you want to get https://www.google.com, then simply do:

// For www.google.com
$scope.baseUrl = $locaton.$$host;
// For https://www.google.com
$scope.baseUrl = $location.$$protocol + '://' + $location.$$host;

Comments

0

Instead of using $scope.baseUrl = '$location.host()

Use this one :-

   $scope.baseUrl = $location.absUrl();

Comments

0

I am late for the party, however I think location.pathname can be better.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.