angular.js directives in different modules

前端 未结 2 1609
无人及你
无人及你 2020-12-16 00:14

I am confused. If I can use ng-app only once per page how can I use directives that sit in different modules, in different .js files. Look:

<         


        
相关标签:
2条回答
  • 2020-12-16 00:50

    There is a solution to bootstrap several angular modules on a page programmatically ( docs ).

    You have to remove ng-app attribute from html.

    Define several modules:

    var app1 = angular.module('myApp1', []);
    
    var app2 = angular.module('myApp2', []);
    
    app1.controller('MainCtrl', function($scope) {
      $scope.name = 'App1';
    });
    
    app2.controller('MainCtrl', function ($scope) {
      $scope.name = 'App2';
    })
    

    And then in index.html do:

      <html>
      <head></head>
      <body>
        <!-- Module 1 -->
        <div id="myApp1">
          <div ng-controller="MainCtrl">
            <h1>Hello {{name}}</h1>
          </div>
        </div>
        <!-- Module 2 -->
        <div id="myApp2">
          <div ng-controller="MainCtrl">
            <h1>Hello {{name}}</h1>
          </div>
        </div>
        <!-- Bootstrap modules -->
        <script>
          angular.element(document).ready(function() {
              angular.bootstrap(document.getElementById('myApp1'), ['myApp1']);
              angular.bootstrap(document.getElementById('myApp2'), ['myApp2']);
         });
        </script>
      </body>
      </html>
    

    Here is a working plnkr with this solution.

    0 讨论(0)
  • 2020-12-16 00:53

    @Agzam, just create a third, top-level, application module that will have dependencies on your sub-modules containing directives:

    <script src='mainModule.js'/>
    <script src='secondModule.js'/>
    <script>
      angular.module('app', ['mainModule', 'secondModule'])
    </script>
    <body ng-app='app'>
       <my-thingy/>
       <div>
          <other-thingy/>
       </div> 
    </body>
    
    0 讨论(0)
提交回复
热议问题