Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

angularjs - Multiple apps and controllers in the same file

In this AngularJS code:

<!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";
    });

  </script>
  <title>Test Controllers</title>
</head>
<body>
  <div ng-app="app1">
    <div ng-controller="Ctrl1">
      <span>{{name}}</span>
    </div>
  </div>
  <div ng-app="app2">
    <div ng-controller="Ctrl2">
      <span>{{name}}</span>
    </div>
  </div>
</body>
</html>

I have two ng-app and two controllers. But only the first one seems to work. The name Jack is shown but Steve does not. Why?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...