如何在使用angular.bootstrap引导角度应用程序后手动初始化控制器?

时间:2014-05-07 11:59:56

标签: javascript angularjs

找到解决这个问题的方法。
我有一个普通的javascript应用程序。我想通过手动引导将我的angularjs应用程序嵌入其中。问题是"具有该模块的控制器根本没有初始化"

的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
 });

但它没有将角度应用嵌入到第一个应用中,收到错误&#34; Argument&#39; MainCtrl&#39;不是一个功能,未定义&#34;

我不明白,我做错了。

只需在 index.html 中引导整个应用,而不是在 scripts.js 中执行此操作

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

感谢!!!

2 个答案:

答案 0 :(得分:1)

陈述的顺序是错误的。它应该是:

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']);

您需要在引导角度应用之前定义控制器。

答案 1 :(得分:-1)

将您的内容包装在:

<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>

更新:手动引导应用程序:

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

更多细节here

我创建了一个fiddle