我用一个 ASP.NET 的MVC应用程序引导了Angular。如何根据正在渲染的 Angular 视图有条件地加载 MVC 捆绑包。
Index.cshtml
<!DOCTYPE html>
<html ng-app="maypp">
<body>
<div class="container">
@*HEADER*@
<div header></div>
<div ui-view></div>
@*FOOTER*@
<div footer></div>
</div>
@Scripts.Render("~/bundles/bundle1")
@Scripts.Render("~/bundles/bundle2")
</body>
</html>
我只需要为角度视图 1 加载捆绑包 1。其他视图需要同时包含捆绑包 1 和捆绑包 2。我使用的是AngularJS,而不是Angular 2。任何回应都值得赞赏。
你可以把它放在cshtml视图的底部。但是,您可能希望将随机数检查器替换为业务逻辑:)
选项 1:
@section Scripts {
@if (new Random().Next(10) > 5)
{
@Scripts.Render("~/bundles/x")
}
else
{
@Scripts.Render("~/bundles/y")
}
}
选项 2:
捆绑包 1:
function startBundleOne(){
//bundle logic
}
捆绑包 2:
function startBundleTwo(){
//bundle logic
}
AngularJS视图:
if (something){
startBundleOne();
} else {
startBundleTwo();
}
选项 3:
var scriptPath;
if (something){
scriptPath = "pathA";
} else {
scriptPath = "pathB";
}
var script = document.createElement('script');
script.setAttribute('src',scriptPath);
document.head.appendChild(script);
您正在使用Angular UI路由器,这样会很容易。创建两个单独的状态,例如捆绑包 1 app1 和捆绑包 2 app2
,如下所示:$stateProvider
.state('app1', {
abstract: true,
url: '/app1',
template: '<div ui-view></div>'
});
$stateProvider
.state('app2', {
abstract: true,
url: '/app2',
template: '<div ui-view></div>'
})
在此之后,使用 oclazyload 库加载不同状态的捆绑包,如下所示:
$stateProvider
.state('app1', {
abstract: true,
url: '/app1',
template: '<div ui-view></div>',
resolve: {
plugins: ['$ocLazyLoad', function($ocLazyLoad) {
return $ocLazyLoad.load([
'~/bundles/bundle1.js'
]);
}]
}
});
$stateProvider
.state('app2', {
abstract: true,
url: '/app2',
template: '<div ui-view></div>',
resolve: {
plugins: ['$ocLazyLoad', function($ocLazyLoad) {
return $ocLazyLoad.load([
'~/bundles/bundle2.js'
]);
}]
}
})
现在,您有两个不同的状态在两个不同的捆绑包中运行。我已经在我的一个项目中实现了这个,它完美地工作。
更新:
angular
.module('myApp')
.config(['$stateProvider', function($stateProvider) {
$stateProvider
.state('app1', {
abstract: true,
url: '/app1',
template: '<div ui-view></div>',
resolve: {
plugins: ['$ocLazyLoad', function($ocLazyLoad) {
return $ocLazyLoad.load([
'~/bundles/bundle1.js'
]);
}]
}
})
.state('app2', {
abstract: true,
url: '/app2',
template: '<div ui-view></div>',
resolve: {
plugins: ['$ocLazyLoad', function($ocLazyLoad) {
return $ocLazyLoad.load([
'~/bundles/bundle2.js'
]);
}]
}
})
}])