Search code examples
javascriptangularjsnestedangularjs-module

Nested modules in AngularJS


I Have 2 differents AngularJs modules : a widgetContainer and a widget.

A widget can be displayed as an independant application or be included into a widgetContainer. A widgetContainer contains 0-N widgets.

If i try to boostrap the widget module into the widgetContainer, angular throw the following error :

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

I have reproduce this error in this plunk

<div id="parentApp">
<div ng-controller="MainParentCtrl">
  Hello {{name}} !
  <div id="childApp">
    <div ng-controller="MainChildCtrl">
      Hello {{childName}} !
    </div>
  </div>
</div>

EDIT :

Using Dependency injection solve the problem efficiently.

Now, I need to load the widget from a directive.

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

    }
  };
}]);

The div is created but the childApp module is not loaded inside. I have updated my plunker


Solution

  • To achieve expected result, use below

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

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

    Syntax for manual bootstrap is as below irrespective of usage of controllers on elements

    angular.bootstrap(element, [modules]);