2016-08-19 222 views
1

我有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

我在this plunk

<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

+0

好像你正試圖從JavaScript兩次引導相同的角模塊相同的元素。參考:https://docs.angularjs.org/error/ng/btstrpd –

回答

1

要在要素達到預期的效果,請使用以下

angular.element(document).ready(function() { 
    angular.bootstrap(document.getElementById('parentApp'), ['parentApp','childApp']); 

}); 

http://plnkr.co/edit/4oGw5ROo80OCtURYMVa3?p=preview

語法手冊自舉如下不論控制器的使用

angular.bootstrap(element, [modules]); 
4

不要試圖引導這兩個模塊。而是使用依賴注入。您只需在您的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']); 
});