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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With