Can I access the MVC web.config values in my modularjs module?
How can I pass my MVC web.config values to my angular module config method?
I want to set the $ logProvider.debugEnabled value with a parameter from my MVC web.config. That way I don't have to forget to change the setting when I go from Dev to Test to Prod.
I have found a solution to pass parameters available from my angular controller, but I need them in my config way.
This is what I have in my app.js application
(function () {
var app = angular.module("myApp", ['configSettings']);
app.config('settings', [function (settings, $logProvider) {
var envr = settings.serverConfig;
if (!envr == "LOCAL") {
$logProvider.debugEnabled(false);
}
}]);
}());
Thanks in advance,
John
source to share
I am using a custom http handler for this:
public class JavascriptResourceHandler : IHttpHandler
{
#region IHttpHandler Members
public bool IsReusable
{
// Return false in case your Managed Handler cannot be reused for another request.
// Usually this would be false in case you have some state information preserved per request.
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
var sb = new StringBuilder();
sb.Append("var js = {};");
sb.Append("js.settings = { ");
var settings = ConfigurationManager.AppSettings.AllKeys.Where(k => k.StartsWith("JS_")).ToList();
for (int i = 0; i < settings.Count; i++)
{
var key = settings[i];
var name = key.Replace("JS_", string.Empty);
var value = ConfigurationManager.AppSettings[key];
sb.Append(name);
sb.Append(":");
sb.Append("'");
sb.Append(HttpUtility.JavaScriptStringEncode(value));
sb.Append("'");
if (i != settings.Count - 1)
sb.Append(",");
}
sb.Append("};");
context.Response.Clear();
context.Response.ContentType = "text/javascript";
context.Response.Write(sb.ToString());
}
#endregion
}
add this handler to <system.webServer><handlers>
:
<add name="JavascriptResourceHandler" verb="GET" path="JavascriptResourceHandler.axd" type="MyNamespace.JavascriptResourceHandler, MyAssembly, Version=1.0.*, Culture=neutral" />
refers to this from html:
<script src="~/JavascriptResourceHandler.axd"></script>
then use the JS_ prefix on the config values to propagate them to javascript (this is for security reasons because we don't want to normally propagate all application settings to client code):
<add key="JS_Key" value="MyConfigValue" />
config values will be available in javascript:
var myValue = js.settings.Key; // the JS_ prefix will be automatically removed
your example:
(function () {
var app = angular.module("myApp", ['configSettings']);
app.config('settings', [function (settings, $logProvider) {
var envr = js.settings.serverAppSettingsKeyWithoutJSPrefix;
if (!envr == "LOCAL") {
$logProvider.debugEnabled(false);
}
}]);
}());
source to share