这是我的问题:我想制作一个单页应用程序,当单击菜单的不同条目时,可以在“主要内容”部分动态加载/卸载 AngularJS 应用程序。
但是我就是不知道怎么做。我总是得到 ng:btstrpd
使用 angular.bootstrap
时出错功能。
我使用以下代码加载应用程序:
var mainContent = document.getElementById('main-content');
window.loadApp = function(modules) {
angular.bootstrap(mainContent, modules);
}
这是一个 jsfiddle:http://jsfiddle.net/010b62ry/
我尝试删除 DOM 元素并再次重新插入它,但出现奇怪的行为(如重复)。我认为模块没有卸载。
我也有很多 <!-- ngView: -->
这样做时发表评论。
有人知道如何实现吗?如果在从一个应用程序切换到另一个应用程序时释放内存,则可加分。
PS:我真的需要引导 100% 独立的模块(管理自己的路由等),因为其中一些可能由无法访问此应用程序源代码的其他人开发。我只需要将他们的模块作为 100% 自主的 Angular 应用程序启动。
最佳答案
我找到了这个帖子 How to destroy an angularjs app? .虽然我添加了代码来重新创建主要内容 div。
HTML代码:
<nav>
<a onclick="loadApp(['app1'])">Load app n°1</a>
<a onclick="loadApp(['app2'])">Load app n°2</a>
</nav>
<div id="main-content-wrap">
<div id="main-content" class="app">
<div ng-view></div>
</div>
</div>
JS:
angular.module('app1', ['ngRoute']);
angular.module('app1')
.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.otherwise({
template: 'hello app n°1'
});
}]);
angular.module('app2', ['ngRoute']);
angular.module('app2')
.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.otherwise({
template: 'hello app n°2'
});
}]);
var mainContent = document.getElementById('main-content');
var mainContentWrap = document.getElementById('main-content-wrap');
var mainContentHTML = mainContentWrap.innerHTML;
window.loadApp = function(modules) {
if (window.currentApp) {
destroyApp(window.currentApp);
mainContentWrap.removeChild(mainContent);
mainContentWrap.innerHTML = mainContentHTML;
mainContent = document.getElementById('main-content');
}
window.currentApp = angular.bootstrap(mainContent, modules);
}
function destroyApp(app) {
/*
* Iterate through the child scopes and kill 'em
* all, because Angular 1.2 won't let us $destroy()
* the $rootScope
*/
var $rootScope = app.get('$rootScope');
var scope = $rootScope.$$childHead;
while (scope) {
var nextScope = scope.$$nextSibling;
scope.$destroy();
scope = nextScope;
}
/*
* Iterate the properties of the $rootScope and delete
* any that possibly were set by us but leave the
* Angular-internal properties and functions intact so we
* can re-use the application.
*/
for(var prop in $rootScope){
if (($rootScope[prop])
&& (prop.indexOf('$$') != 0)
&& (typeof($rootScope[prop]) === 'object')
) {
$rootScope[prop] = null;
}
}
}
和 fiddle http://jsfiddle.net/010b62ry/5/
它有效,但它看起来像黑魔法。我认为拥有一个应用程序和多个 Controller 要好得多。
关于javascript - 使用 angular.bootstrap 手动加载/卸载模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26146657/