在实践中,发现如果一个页面有多个ng-app,angular只会处理第一个ng-app
相关问题:
单个angular页面能否有两个ng-app 开源中国社区
http://stackoverflow.com/questions/18571301/angularjs-multiple-ng-app-within-a-page
问题重现:
<!Doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style> </style>
<script src="js/jquery.min.js"></script>
<script src ="js/angular.js"></script>
<script >
var app = angular.module("myapp",[]);
app.directive("hello",function(){
return {
restrict:"E",
template:'<h1>Hello angular</h1>',
replace:true
}
});
var app2 = angular.module("dir",[]).run(function($templateCache){
$templateCache.put("header.html","<h2>use templateCache</h2>");
});
app2.directive("dir",function($templateCache){return {
restrict:"E",
template:$templateCache.get("header.html"),
replace:true
}});
</script>
</head>
<body >
<div ng-app="myapp">
<hello></hello>
</div>
<div ng-app="dir">
<dir></dir>
</div>
</body>
</html>
运行后只会输出:
Hello angular
解决办法:
使用angular.bootstrap
手动将第二个ng-app加入控制:
在,js代码最后加上一句:
angular.bootstrap($("dir"),['dir']);
当然,在第二个ng-app接管的div上要加一个id属性dir并且去掉第二个ng-app。
所以最终两个ng-app能同时存在于一个页面的完整示例代码是:
<!Doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style> </style>
<script src="js/jquery.min.js"></script>
<script src ="js/angular.js"></script>
</head>
<body >
<div ng-app="myapp">
<hello></hello>
</div>
<div id="dir" >
<dir></dir>
</div>
<script >
var app = angular.module("myapp",[]);
app.directive("hello",function(){
return {
restrict:"E",
template:'<h1>Hello angular</h1>',
replace:true
}
});
var app2 = angular.module("dir",[]).run(function($templateCache){
$templateCache.put("header.html","<h2>use templateCache</h2>");
});
app2.directive("dir",function($templateCache){return {
restrict:"E",
template:$templateCache.get("header.html"),
replace:true
}});
angular.bootstrap($("dir"),['dir']);
</script>
</body>
</html>
对于angular.bootstrap的一点探讨:
1.使用ng-app,页面加载时会这样处理:
- angular找到ng-app标记后,首先加载与module相关的directive
- 创建应用相关的injector(依赖管理器)
- 开始对ng-app为根节点的DOM“编译”
2、angular.bootstrap方法可以理解为省去查找ng-app的过程,传给bootstrap的参数一个为DOM对象,另一个为模块名数组。