【问题标题】:How to initialize controllers manually after bootstrapping angular app using angular.bootstrap?如何在使用 angular.bootstrap 引导 Angular 应用程序后手动初始化控制器?
【发布时间】:2014-06-24 09:31:21
【问题描述】:

找到了这个问题的解决方案。
我有一个普通的 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
 });

但它没有将 Angular 应用程序嵌入到第一个应用程序中,出现错误 “Argument 'MainCtrl' is not a function, got undefined”

我不明白,我哪里做错了。

只需在 index.html 中引导整个应用程序,而不是像这样在 scripts.js 中这样做

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

谢谢!!!

【问题讨论】:

标签: javascript angularjs


【解决方案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']);

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

【讨论】:

    【解决方案2】:

    将您的内容包装在:

    <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

    【讨论】:

    • OPs 方法的重点是不自动引导 Angular 应用程序。 (意思是:不使用ng-app 属性。)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-15
    • 1970-01-01
    • 2014-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多