0

My angularJS application is running in a web server with the following path

http://www.some.domain.com/some/path/

Notice that /some/path/ is dynamic path because my app can be deployed to any web server to any directory. I need to get this absolute URL in AngularJS excluding all inner angular pages. For instance, if current user's page is

http://www.some.domain.com/some/path/inner/angular/page.html

then the code that I am looking for should return

http://www.some.domain.com/some/path/
4
  • docs.angularjs.org/guide/$location. Specifically, $location.host() should return what you want. Commented Jan 4, 2016 at 12:57
  • Are you using Angulars own routing? You might want to check here, see if any of that would help you: docs.angularjs.org/api/ng/service/$location Commented Jan 4, 2016 at 12:58
  • A couple of methods I have used: when using a build system for my client-side app (almost always) AND the context root is known at build time, I set an Angular constant through the build system (e.g. grunt-ng-constant/gulp-ng-constant). Sometimes I make the main HTML page dynamic (JSP in my case) and set a global JS var with a scriptlet: var contextPath = '<%= request.getContextPath() %>';. Otherwise (but least preferably) URL sniffing - e.g. through $location. Commented Jan 4, 2016 at 13:04
  • @NikosParaskevopoulos yeah I supply context root as a grunt parameter, so I know the context root in advance. However, I thought there is an easier way to get context root AND domain, port of the web server my app is running on. Commented Jan 4, 2016 at 16:39

2 Answers 2

1

You cannot use $location because it only has information about the current SPA.

The code that you are looking for ("/some/path/") is this:

var myContextWithPath = $window.location.pathname.substring(0, window.location.pathname.lastIndexOf("/"));

Other variation that returns only the context ("/some") is this:

var myContext = $window.location.pathname.substring(0, window.location.pathname.indexOf("/",2));

You can also obtain the origin ("http://www.some.domain.com"):

var origin = $window.location.origin;
Sign up to request clarification or add additional context in comments.

Comments

0

You can use $location for this. Don't forget the add $location in to controller function

$location.host()

gives you base url.Which is application base server domain, like : www.example.com

$location.port()

gives you port like : 8080

$location.path()

gives you where you are : index.html

1 Comment

Yeah, I know this, I thought there must be some handy utility for doing it. But thanks anyway.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.