简体   繁体   中英

How to initialize controllers manually after bootstrapping angular app using angular.bootstrap?

Found solution to this question.
I have a normal javascript app.I want to embed my angularjs app into it by bootstrapping manually.The problem is that "controllers with that module is not at all initialized"

index.html:

<html>
  <head> <title>Including angular app into another</title> </head>
  <body>
    //I have normal javascript app
    <div>First App</div>

    <div id="secondApp">
      <div class="container" ng-include="'views/main.html'" ng-controller="MainCtrl"> </div>
    </div>
    //included all libraries required for the app
    <script src="jquery.js"></script>
    <script src="angular.js"></script>
    //main.js
    <script src="scripts.js"></script>
  </body>
</html>

scripts.js:

angular.module('sampleApp', []);
// in this way, i have bootstrapped the app
angular.bootstrap(document.getElementById('secondApp'), ['sampleApp']);

angular.module('sampleApp')
 .controller('MainCtrl', function($scope, $rootScope, $timeout) {
   //i have included the functionality required for my second app
 });

But it is not embedding angular app into first app, getting an error "Argument 'MainCtrl' is not a function, got undefined"

I don't understand, where i am doing wrong.

Just bootstrap the whole app in index.html instead of doing this in scripts.js like this

<script type="text/javascript">
  angular.element(document).ready(function() {
    angular.bootstrap(document.getElementById('secondApp'), ['assetWidgetApp']);
 });
</script>

Thanks!!!

The order of the statements is wrong. It should be:

angular.module('sampleApp', []);

angular.module('sampleApp')
 .controller('MainCtrl', function($scope, $rootScope, $timeout) {
   //i have included the functionality required for my second app
 });

// in this way, i have bootstrapped the app
angular.bootstrap(document.getElementById('secondApp'), ['sampleApp']);

You need to define the controller before you bootstrap the angular app.

Wrap your content in:

<div ng-app="sampleApp">
    <div>First App</div>

    <div id="secondApp">
      <div class="container" ng-include="'views/main.html'" ng-controller="MainCtrl"> </div>
    </div>
    //included all libraries required for the app
    <script src="jquery.js"></script>
    <script src="angular.js"></script>
    //main.js
    <script src="scripts.js"></script>
</div>

UPDATE: to bootstrap the app manually:

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

More detailse here

I have created a fiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM