The way I do such things is pretty much the same as you suggest (using JSON.net and Razor):
- I am preparing a dictionary or an object graph with the data that I want to make available.
- Passing data as part of a ViewModel from a controller to a view
- Serialize ViewModel data by entering it in the
cshtml template as a global JavaScript variable. I have to use the following trick to get this working:
<script> var AppSettings = (function(o) { return o; })(@Html.Raw(JsonConvert.SerializeObject(Model.AppSettings))); </script>
- Create an angular service that reads (and copies) the global JavaScript variable.
- Data clients access it through the angular service.
A service is just a thin shell, although sometimes it contains logical and accessory methods. The value here is that you access a global variable (dirty practice in the angular world) from only one place in your code. "Encapsulate ugly things!"
Note. This requires your angular app to be sent from the MVC website using the cshtml template.
The advantage of this approach when creating an AJAX call is that the data of interest is available immediately after loading the angular application ... the data can be accessed through the service synchronously. This simplifies data access. If asynchrony is fine, I would suggest making an AJAX call from your service, cache the result, and return the promise. With the AJAX approach, there is no connection between the angular template and your MVC project, which allows you to serve your angular template as a simple html file.
source share