多个应用程序和控制器在同一文件 [英] Multiple apps and controllers in the same file

查看:118
本文介绍了多个应用程序和控制器在同一文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此AngularJS code:

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>

我有两个NG-应用和两个控制器。但只有第一个似乎工作。这个名字是杰克显示,但史蒂夫没有。为什么呢?

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?

推荐答案

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

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

一个NG-程序指令的自动初始化仅发生一次,但你可以手动初始化使用引导方法附加模块。 (参见:<一href=\"https://docs.angularjs.org/guide/bootstrap\">https://docs.angularjs.org/guide/bootstrap)

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)

与解决方案的jsfiddle是在这里: http://jsfiddle.net/DEnB2/5/

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>

这篇关于多个应用程序和控制器在同一文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆