在主 MVC cshtml 文件的 <script> 标记中,放置主模块并根据您想要访问这些值的时间添加值或常量。
<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>
有一个“极端”的选择。与您想要实现的目标类似。
如果您自己创建了一个 JS 框架并将其包含在 _Layout.cshtml 中的 angular 之前,那么您可以在主 .cshtml 文件中设置其变量,并且 angular 可以在整个过程中使用它。
框架(在您的 _Layout.cs 中或作为布局中包含的另一个 js 文件):
<script>
(function (context) {
context.my = {
serverUrl: "hey"
};
})(this);
</script>
在主.cshtml:
<script>
my.serverUrl = '@serverUrl';
</script>
在你的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);