AngularJS中的嵌套模块
问题描述:
我有2个不同的AngularJs模块:一个widgetContainer和一个小部件。AngularJS中的嵌套模块
小部件可以显示为独立应用程序或包含在widgetContainer中。 widgetContainer包含0-N小部件。
,如果我尝试自举的微件模块到widgetContainer,角引发以下错误:
Error: [ng:btstrpd] App already bootstrapped with this element '<div id="childApp">' http://errors.angularjs.org/1.5.8/ng/btstrpd?p0=%26lt%3Bdiv%20id%3D%22childApp%22%26gt%3B
<div id="parentApp">
<div ng-controller="MainParentCtrl">
Hello {{name}} !
<div id="childApp">
<div ng-controller="MainChildCtrl">
Hello {{childName}} !
</div>
</div>
</div>
编辑重现此错误:
使用依赖注入解决pr高效地使用。
现在,我需要从指令中加载小部件。
parentApp.directive('widget', [function() {
return {
restrict: 'E',
link: function($scope, $element, $attr) {
var div = document.createElement('div');
div.setAttribute("ng-controller", "MainChildCtrl");
div.innerHTML = 'Hello {{childName}} !';
$element.append(angular.element(div));
}
};
}]);
创建了div,但childApp模块没有加载到里面。 我已经更新了我的plunker
答
要在要素达到预期的效果,请使用以下
angular.element(document).ready(function() {
angular.bootstrap(document.getElementById('parentApp'), ['parentApp','childApp']);
});
http://plnkr.co/edit/4oGw5ROo80OCtURYMVa3?p=preview
语法手册自举如下不论控制器的使用
angular.bootstrap(element, [modules]);
答
不要试图引导这两个模块。而是使用依赖注入。您只需在您的html中声明一个模块,然后使用角码将该模块依赖于其他模块。在这里看到:https://docs.angularjs.org/guide/concepts#module
这是你的更新plunkr:http://plnkr.co/edit/DJvzpCoxLRhyBl77S27k?p=preview
HTML:
<body>
<div id="childApp">
<div ng-controller="MainParentCtrl">
Hello {{name}} !
<div>
<div ng-controller="MainChildCtrl">
Hello {{childName}} !
</div>
</div>
</div>
</div>
</body>
AngularJS:
var parentApp = angular.module('parentApp', [])
.controller('MainParentCtrl', function($scope) {
$scope.name = 'universe';
});
var childApp = angular.module('childApp', ['parentApp'])
.controller('MainChildCtrl', function($scope) {
$scope.childName = 'world';
});
angular.element(document).ready(function() {
angular.bootstrap(document.getElementById('childApp'), ['childApp']);
});
好像你正试图从JavaScript两次引导相同的角模块相同的元素。参考:https://docs.angularjs.org/error/ng/btstrpd –