Best way to provide url to angular $http.get/.post

Shumii picture Shumii · Jan 9, 2014 · Viewed 12k times · Source

I am using angular with MVC4. I would like to call a MVC controller method from javascript using $http.get(). It requires a url (obviously). I would like this to be a relative path, but how do I write that? My controller is in Controllers/Api/ExampleController. I would like the path to resolve even if I move the javascript file into another location, meaning I would like the path to be relative to application root as opposed to the javascript file. I Have tried "~/Controllers/Api/ExampleControllerMethod" and "Controllers/Api/ExampleController/Method.

Answer

Davin Tryon picture Davin Tryon · Jan 9, 2014

The $location service does provide information from the url. So, you could construct something to then make the host and port dynamic:

var url = $location.host() + '/Controllers/Api/ExampleControllerMethod';

From the documentation:

**url: http://www.example.com/base/path?a=b#h**
$location.protocol() = http
$location.host() = www.example.com
$location.port() = 80
$location.path() = /path
$location.search() = {"a":"b"}
$location.hash() = h