In the <script> tag of the main MVC cshtml file put the main module and add a values or constant depending on when you want access to these values.
<script>
(function (angular) {
'use strict';
angular.module('main.app', [
// examples of external dependencies
'ui.bootstrap',
'ui.router',
// examples of internal dependencies
'login.module',
'register.module'
])
.constant('MvcValues', mvcValues());
// constant allows use in the config and run phase of an angular application lifecycle
function mvcValues() {
return {
'serverUrl': '@serverUrl'
}
}
})(angular);
</script>
// in another file
<script>
(function (angular) {
'use strict';
angular.module('login.module', [])
.controller('loginController', ['MvcValues', loginController]);
function loginController(MvcValues) {
var vm = this;
vm.serverUrl = MvcValues.serverUrl;
}
})(angular);
</script>
There is an "extreme" alternative. Similar to what you were trying to achieve.
If you create yourself a JS framework and include it before angular in your _Layout.cshtml then you can set its variable in the main .cshtml file and angular can use it throughout.
Framework (in your _Layout.cs or as another js file included in the layout):
<script>
(function (context) {
context.my = {
serverUrl: "hey"
};
})(this);
</script>
In main .cshtml:
<script>
my.serverUrl = '@serverUrl';
</script>
In your app.js:
(function (angular) {
'use strict';
angular.module('main.app', [
// examples of external dependencies
'ui.bootstrap',
'ui.router',
// examples of internal dependencies
'login.module',
'register.module'
])
.constant('MvcValues', my); //<-- see here we injected the framework into a constant
// constant allows use in the config and run phase of an angular application lifecycle
})(angular);