Multiple apps and controllers in the same file

后端 未结 2 1756
攒了一身酷
攒了一身酷 2020-12-16 08:09

In this AngularJS code:




  

        
相关标签:
2条回答
  • 2020-12-16 08:51

    The JSFiddle showing the problem is here: http://jsfiddle.net/DEnB2/

    Automatic initialization of a ng-app directive occurs only once but you can manually initialize additional modules using the bootstrapping method. (See: https://docs.angularjs.org/guide/bootstrap)

    The JSFiddle with the solution is here: http://jsfiddle.net/DEnB2/5/

    <!DOCTYPE html>
    <html>
    <head>
      <script src="http://code.angularjs.org/1.2.9/angular.min.js" type="text/javascript"></script>
      <script>
        var app1 = angular.module('app1', []);
    
        app1.controller('Ctrl1', function ($scope)
        {
          $scope.name = "Jack";
        });
    
        var app2 = angular.module('app2', []);
    
        app2.controller('Ctrl2', function ($scope)
        {
          $scope.name = "Steve";
        });
    
        angular.element(document).ready(function() {
          angular.bootstrap(document.getElementById('app2'), ['app2']);
        });   
      </script>
      <title>Test Controllers</title>
    </head>
    <body>
      <div ng-app="app1">
        <div ng-controller="Ctrl1">
          <span>{{name}}</span>
        </div>
      </div>
      <div id="app2">
        <div ng-controller="Ctrl2">
          <span>{{name}}</span>
        </div>
      </div>
    </body>
    </html>
    
    0 讨论(0)
  • 2020-12-16 09:04

    According understand only a single standing-ng app. Here's an alternative for you to work on the two controllers. I would like to know why you need two-ng app?

    <head>
        <script src="http://code.angularjs.org/1.2.9/angular.min.js" type="text/javascript"></script>
        <script>
            var app1 = angular.module('app1', []);
    
            app1.controller('Ctrl1', function ($scope)
            {
                $scope.name = "Jack";
            });
    
            app1.controller('Ctrl2', function ($scope)
            {
                $scope.name = "Steve";
            });
    
        </script>
        <title>Test Controllers</title>
    </head>
    <body ng-app="app1">
    
        <div ng-controller="Ctrl1">
            <span>{{name}}</span>
        </div>
    
    
        <div ng-controller="Ctrl2">
            <span>{{name}}</span>
        </div>
    
    </body>
    

    0 讨论(0)
提交回复
热议问题