Reputation: 7601
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/
.
Upvotes: 21
Views: 56728
Reputation: 5048
I am late for the party, however I think location.pathname
can be better.
Upvotes: 0
Reputation: 3355
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
Upvotes: 3
Reputation: 2848
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.
Upvotes: 4
Reputation: 301
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.
Upvotes: 17
Reputation: 1117
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;
Upvotes: 2
Reputation: 21
Instead of using $scope.baseUrl = '$location.host()
Use this one :-
$scope.baseUrl = $location.absUrl();
Upvotes: 0
Reputation: 449
To get just the baseurl and nothing else use
$browser.baseHref()
it will return something like
/central/
Upvotes: 10
Reputation: 39018
Try this: $location.$$absUrl
console.log('$location',$location.$$absUrl);
btw /localhost
is your base path, but I guess you meant entire URL.
Upvotes: 15