I wanted a ASP .NET MVC view (*.cshtml) to render on the server and pass the static text contained in the the ASP .NET project resource file to an Angular controller, so on the initial page request, all static data is returned to the client. Dynamic data, like grid content would then be requested by a separate JSON call.
The resource data is passed to the Angular controller by using ng-init.
For the sake of this blog post I stuffed everything in one *.cshtml page, including CSS en JavaScript.
Of course this would be separate files in an real application.
Project resource file
Layout.cshtml
<!DOCTYPE html> <html xmlns:ng="http://angularjs.org" id="ng-app" ng-app="app"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Send initialization data from HTML to Angular controller</title> <style> /* Add some initial styling. */ html, body { background-color: #F1F1F1; font-family: "Open Sans", sans-serif; font-size: 13px; height: 100%; } body { margin: 20px; } [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak { display: none !important; } </style> <!-- Library scripts --> <script src="https://code.angularjs.org/1.4.1/angular.min.js"></script> </head> <body ng-cloak> @RenderBody() <div> <div ng-controller="main" ng-init="resources={ textFromResource: '@WebApplication1.Properties.Resources.TextFromResource'}"> <h1>{{ title }}</h1> {{ resources.textFromResource }} </div> </div> <script> // Angular module. (function () { "use strict"; angular .module("app", []); }()); // Angular controller. (function () { "use strict"; function controller($scope) { $scope.title = "Show ASP .NET MVC resoure (*.resx) data to user on initial load."; } angular .module("app") .controller("main", ["$scope", controller]); }()); </script> </body> </html>
Result
Thank you for this post!
I had been trying to do this all day with no success until I found this post.
Thank you, thank you, thank you 🙂