有两个问题需要解决:
- 将
web.config 值导入 Angular 应用程序
- 利用配置下载脚本
1.将 web.config 获取到应用程序:
我已经在a blog post 中详细说明了我使用的方法。本质上,在应用程序.cshtml 文件中使用自定义角度提供程序。这将加载前缀为 client: 的所有 web.config 项目...
由 MVC 控制器使用:
public static class ApplicationConfiguration
{
private const string ClientAppSettingPrefix = "client:";
public static object GetClientConfiguration()
{
var clientConfiguration = new ExpandoObject() as IDictionary<string, Object>;
// Find all appSetting entries prefixed with "client:"
foreach (var key in ConfigurationManager.AppSettings.AllKeys.Where(key => key.StartsWith(ClientAppSettingPrefix)))
{
// Remove the "client:" prefix before adding to clientConfiguration
clientConfiguration.Add(key.Replace(ClientAppSettingPrefix, String.Empty), ConfigurationManager.AppSettings[key]);
}
return clientConfiguration;
}
}
脚本已添加到应用的 .cshtml 文件中:
<!-- Inject the configuration -->
<script type="text/javascript">
(function() {
angular.module('client.config', [])
.provider('applicationConfiguration', function() {
var config = @Html.Raw(JsonConvert.SerializeObject(Model, new JsonSerializerSettings {ContractResolver = new CamelCasePropertyNamesContractResolver()}));
return {
config: config,
$get: function() {
return config;
}
};
});
})();
</script>
所以现在您可以在添加时使用它作为普通依赖项:
angular.module('app', [
// Add as a dependent module
'client.config'
])
.config([
'applicationConfigurationProvider', 'dataServiceProvider', function(applicationConfigurationProvider, dataServiceProvider) {
// Set the api root server configuration
dataServiceProvider.setApiRootUrl(applicationConfigurationProvider.config.apiRoot);
}
]);
2。利用config下载脚本
正如其他答案中所建议的,使用 JQuery 的 getScript() 函数。
如果您不想依赖 Jquery,其他 SO 答案也建议使用简单的注入 head。看看Single page application - load js file dynamically based on partial view 的想法