同一文件中的多个应用和控制器

时间:2014-07-21 14:25:58

标签: angularjs

在这个AngularJS代码中:

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

我有两个ng-app和两个控制器。但只有第一个似乎有效。杰克的名字显示但史蒂夫没有。为什么呢?

2 个答案:

答案 0 :(得分:9)

显示问题的JSFiddle在这里:http://jsfiddle.net/DEnB2/

ng-app指令的自动初始化仅发生一次,但您可以使用bootstrapping方法手动初始化其他模块。 (见:https://docs.angularjs.org/guide/bootstrap

解决方案的JSFiddle在这里: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>

答案 1 :(得分:0)

根据只了解一个常设应用程序。这是您使用两个控制器的替代方案。我想知道你为什么需要2-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>