Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get host+base from angular $location

Tags:

angularjs

I have angular application located in directory 'someApp'. Url is http://example-domain/someApp/#/ for some state url with path is: http://example-domain/someApp/#/user/login. I there "angular way" to get this part http://example-domain/someApp/

var redirectUri = $location.absUrl();
redirectUri = redirectUri.substr(0, redirectUri.indexOf('#'));
like image 767
Styx Avatar asked Sep 08 '15 18:09

Styx


2 Answers

The easiest way is to use

window.location.origin + window.location.pathname

which would return http://example-domain/someApp

This will provide the entire base url, even if using virtual directories/paths. However, IE does not support origin. As a result, you could concatenate the components of the url to give you the base directory like so:

window.location.protocol + "//" + window.location.hostname + window.location.pathname

which would return http://example-domain/someApp

If using virtual directories, you will have difficulty using $location, since $location.path() returns AFTER the hash and $location.host() will only return the domain, not the domain and the directory, which is what window.location.hostname + window.location.pathname gives you.

like image 75
David L Avatar answered Oct 15 '22 07:10

David L


You need to use:

 location.origin + location.pathname

Say the url is http://example.com/#/some/path?foo=bar&baz=xoxo

$location.protocol(); // will give: http
$location.host();     // will give: example.com
location.host         // will give: example.com:8080
$location.port();     // will give: 8080
$location.path();     // will give: /some/path
$location.url();      // will give: /some/path?foo=bar&baz=xoxo

See the full detail

like image 36
Ali Adravi Avatar answered Oct 15 '22 08:10

Ali Adravi