Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi modules in one page with angularjs

How to use multi modules in one single page in angular?

I read some docs and they say I can't use ngApp directive and should use angular.bootstrap.

My HTML code:

<div id="M1">
  <div ng-controller="Ctrl">
     <h1>Hello {{name}}</h1>
  </div>
</div>
<div id="M2">
  <div ng-controller="Ctrl">
    [{{name}}]
  </div>
</div>

My angular code:

var m1 = angular.module('M1', []);

m1.controller('Ctrl', function($scope) {
  $scope.name = 'M1';
});

var module2 = angular.module('M2', []);
module2.controller('Ctrl', function($scope){
$scope.name = 'M2';
})

angular.bootstrap(document.getElementById('M1'), ['M1']);
angular.bootstrap(document.getElementById('M2'), ['M2']);

But it doesn't work.

This is a live demo: http://plnkr.co/edit/dkyL8eacoC5ZohfwSWz1?p=preview

like image 808
Freewind Avatar asked Feb 17 '23 01:02

Freewind


1 Answers

Seems like the bootstrapping is occurring too soon. Modify the two boostrap lines to happen when the document is ready:

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

When modifying your plnkr in this way, both apps started working properly.

Live demo: http://plnkr.co/edit/Of0PYWR5ZEGT5BK4sfhI?p=preview

like image 128
Ryan O'Neill Avatar answered Feb 26 '23 22:02

Ryan O'Neill