0

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?

Tân
  • 1
  • 15
  • 56
  • 102
  • 1
    You can only have one `ng-app` directive which bootstraps automatically. If you have multiple modules, you'll have to bootstrap them yourself. See [this answer](http://stackoverflow.com/a/12864137/3153169) for reference – devqon Nov 28 '16 at 10:26
  • Check [ngApp](https://docs.angularjs.org/api/ng/directive/ngApp). Only one AngularJS application can be auto-bootstrapped per HTML document (using `ng-app`) – taguenizy Nov 28 '16 at 10:27

1 Answers1

1

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']);
    });
})();
lenilsondc
  • 9,590
  • 2
  • 25
  • 40