I need to read web.config appsettings in MVC controller method and pass them to view and access the settings in angularjs controller and service. I am thinking to loop through the appsettings and prepare a dictionary with key/value pairs and pass it a model object to my view. But how can I access them anywhere in the angular application?
The way I do this sort of thing is pretty much just as you suggest (using JSON.net and Razor):
cshtml
template as a global JavaScript variable. I have to use the following trick to get this to work:<script>
var AppSettings = (function(o) {
return o;
})(@Html.Raw(JsonConvert.SerializeObject(Model.AppSettings)));
</script>
The service is just a thin wrapper, though sometimes it contains logic and accessor methods. The value here is that you are only accessing the global variable (a 'dirty' practice in the angular world) from only one spot in your code. "Encapsulate the ugly stuff!"
Note: This does require that your angular app is served from the MVC website via a cshtml
template.
The advantage of this approach over making an AJAX call is that the data of interest is available right when the angular app is bootstrapped... the data can be accessed via the service synchronously. This simplifies access to the data. If asynchrony is OK, I would suggest making an AJAX call from your service, caching the result, and returning a promise. With the AJAX approach there is no coupling between the angular template and your MVC project, allowing you to serve your angular template as a plain html file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With