Tân Nguyễn Tân Nguyễn - 5 days ago 6
AngularJS Question

How to call a module multiple times?

startupModule.js
:

(function () {
'use strict';

let app = angular.module('startupModule', []);

app.controller('controller1', function () {
// do this work on loading...
});

app.controller('controller2', function () {
// do this work on loading...
});
}());


loginModule.js
:

(function () {
'use strict';

let app = angular.module('loginModule', []);

app.controller('loginController', function () {

});
}());


In the view:

<div ng-app="startupModule" ng-controller="controller1">

</div>

<div ng-app="loginModule" ng-controller="loginController">

</div>

<div ng-app="startupModule" ng-controller="controller2">

</div>


On loading, I want to call controllers
controller1
and
controller2
to do some works automatically.
loginModule
is the main module that I want to use and it cannot be removed or combined with
startupModule
.

When I run it, there was no error in
Console
. But the controller
controller2
in the third div cannot be excuted, because
ng-app="startupModule"
cannot be recalled (I guess).

To check again, I've removed
ng-app="startupController" ng-controller="controller1"
in the first div. Then,
controller2
should work.

My question: how can I call a module via calling
ng-app
multiple times?

Answer

According to AngularJs docs for `ngApp,

only one AngularJS application can be auto-bootstrapped per HTML document. The first ngApp found in the document will be used to define the root element to auto-bootstrap as an application. To run multiple applications in an HTML document you must manually bootstrap them using angular.bootstrap instead.

So, you have to bootstrap your modules manually. For example:

<div id="app1" ng-controller="controller1"></div>    
<div id="app2" ng-controller="loginController"></div>    
<div id="app3" ng-controller="controller2"></div>

So that from javascript you can bootstrap them:

(function () {
    'use strict';

    var 
        app1 = document.getElementById('app1'),
        app2 = document.getElementById('app2'),
        app3 = document.getElementById('app3');

    angular.element(document).ready(function () {
        angular.bootstrap(app1 , ['startupModule']);
        angular.bootstrap(app2 , ['loginModule']);
        angular.bootstrap(app3 , ['startupModule']);
    });
})();
Comments