Nested modules in AngularJS

早过忘川 提交于 2020-01-04 05:14:28

问题


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


回答1:


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



回答2:


Don't try to bootstrap both modules. Instead use dependency injection. You only declare one module in your html and you make that module depend upon the other module using angular code. See here: https://docs.angularjs.org/guide/concepts#module

Here's your updated 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']);
});


来源:https://stackoverflow.com/questions/39044175/nested-modules-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!