使用angular.bootstrap手动加载/卸载模块?

时间:2014-10-01 17:03:17

标签: javascript angularjs

这是我的问题:我想创建一个单页面应用程序,在单击菜单的不同条目时,可以在“主要内容”部分中即时加载/卸载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%自主角应用程序启动。

1 个答案:

答案 0 :(得分:2)

我找到了这个帖子How to destroy an angularjs app?。虽然我添加了代码来重新创建主内容div。

HTML code:

<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;
        }
    }
}

和小提琴http://jsfiddle.net/010b62ry/5/

它有效,但它看起来像黑魔法。我认为拥有一个应用程序和几个控制器要好得多。

相关问题