解决angular单个页面只能加载一个ng-app的问题

在实践中,发现如果一个页面有多个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,页面加载时会这样处理:

  1. angular找到ng-app标记后,首先加载与module相关的directive
  2. 创建应用相关的injector(依赖管理器)
  3. 开始对ng-app为根节点的DOM“编译”

2、angular.bootstrap方法可以理解为省去查找ng-app的过程,传给bootstrap的参数一个为DOM对象,另一个为模块名数组。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值