AngularJS 在同一个界面启动多个ng-app应用模块详解

2019-11-26,,,

AngularJS默认在一个html界面中只启动一个

 ng-app 模块,而且是界面中第一次出现的那个使用 ng-app 声明的模块,该问题可以通过查看AngularJS源代码或者是文档验证。

解决方案:

直接上代码,如果有兴趣了解其中缘由,可以选择阅读后面的部分;

<!DOCTYPE html>
<html>
<head lang="zh_CN">
 <meta charset="UTF-8">
 <title>AngularJS Source Code Analysis</title>
 <script src="source/angular.min.js" type="text/javascript"></script>
 <script src="source/angular-route.min.js" type="text/javascript"></script>
</head>
<body>
 <div ng-app="myApp-0" ng-controller="nameCtrl">
 <input type="text" ng-model="age"/>{{ demo }}--{{ age }}
 <ul>
  <li ng-repeat="val in names" ng-bind="val"></li>
 </ul>
 </div>

 <!-- 并行启动多个ng-app -->
 <div id="test-0" ng-controller="testCtrl_0">
 <p>{{content.message}}</p>
 </div>
 <div id="test-1" ng-controller="testCtrl_1">
 <p>{{content.message}}</p>
 </div>
</body>
<script>
 var myApp_0 = angular.module("myApp-0", []);
 myApp_0.controller('nameCtrl', function ($scope, $rootScope){
 $scope.names = ["shen", "amy", "sereno"];
 $scope.age = 24;
 $rootScope.demo = "demo";
 });

 var myApp_1 = angular.module("myApp-1", []);
 myApp_1.controller('nameCtrl-1', function ($scope, $rootScope){
 $scope.names = ["shen-1", "amy-1", "sereno-1"];
 $rootScope.age = 24;
 });


 // 并行启动多个 ng-app
 var myApp1mod = angular.module('test-0',[]);
 myApp1mod.controller('testCtrl_0',function($scope){
 var content= {};
 content.message = "Hello Test-0";
 $scope.content= content;
 });

 var myApp2mod = angular.module('test-1',[]);
 myApp2mod.controller('testCtrl_1',function($scope){
 var content= {};
 content.message = "Hello Test-1";
 $scope.content= content;
 });

 angular.element(document).ready(
  function (){
  angular.bootstrap(document.getElementById("test-0"), ["test-0"]);
  angular.bootstrap(document.getElementById("test-1"), ["test-1"]);
  }
 );

</script>
</html>



感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

您可能感兴趣的文章:

  • AngularJS使用ng-app自动加载bootstrap框架问题分析
  • AngularJS框架的ng-app指令与自动加载实现方法分析
  • AngularJS ng-app 指令实例详解
  • 基于AngularJS实现页面滚动到底自动加载数据的功能
  • AngularJS入门示例之Hello World详解
  • Angularjs通过指令监听ng-repeat渲染完成后执行脚本的方法
  • angularjs中ng-attr的用法详解
  • Angularjs中ng-repeat-start与ng-repeat-end的用法实例介绍
  • AngularJS实现网站换肤实例
  • AngularJS使用带属性值的ng-app指令实现自定义模块自动加载的方法

《AngularJS 在同一个界面启动多个ng-app应用模块详解.doc》

下载本文的Word格式文档,以方便收藏与打印。