Edit
If you just need to get the URL of the root / base of the site to add it to get a different URL, you can just use / as the first character of your URL.
var getUsersUrl = "/api/users";
An alternative approach for creating a relative URL using helper methods is MVC.
Because the url pattern is wrong! Javascript cannot convert your ~ to a base application path like a razor. If you check the browser network tab, you may see a 404 error.
You do not have to hardcode your base path to your application. You can use the Url.Content or Url.RouteUrl helper methods in your razor mode to generate the URL in the application database. It will take care of the proper construction of the URL regardless of the current page / path. When you get this value, assign it to the javascript variable and use this in your other js code to create other urls. Always avoid using the javascript namespace in this case to avoid possible problems with javascript global variables.
So in your razor mode (layout file or specific view) you can do this
<script> var myApp = myApp || {}; myApp.Urls = myApp.Urls || {}; myApp.Urls.baseUrl = '@Url.Content("~")'; </script> <script src="~/Scripts/AngularControllerForPage.js"></script> <script> var a = angular.module("app").value("appSettings", myApp); </script>
And in your angular controllers / files you can access it, e.g.
var app = angular.module("app", []); var ctrl = function (appSettings) { var vm = this; vm.baseUrl = appSettings.Urls.baseUrl;
You can and should access this in your data services, directives, etc.
(function () { angular.module("app") .directive("areaOne", function (appSettings) { return { restrict: 'E', templateUrl: appSettings.Urls.baseUrl+'/templates/area1.html', controller: function ($scope) { $scope.button1Click = function () { alert("button1 clicked"); } } } }); })();
Shyju Dec 23 '15 at 2:08 2015-12-23 02:08
source share