前言
当我们在写一个web应用的时候,很常见的情况就是一个页面的部分内容会在另一个页面用到,如果我们为这里相同的两个页面分别写模板,虽然不是很麻烦,但是这样重复造轮子的行为实在是不可取的,特殊场景除外。这个时候我们容易想到将之前的页面复用,angularjs提供了ng-include指令来满足这样的场景。
原理
ng-include实际是通过一个新生成的子scope来继承父controller中的scope,从而调用父controller中的元素。
在网上看了一个简单的demo如下:
<div ng-controller="myController5 as Ctr5"> <div ng-include src="'template1.html'"></div> <div ng-include src="'template2.html'"></div> </div> <script type="text/ng-template" id="/template1.html"> <input ng-model="Ctr5.string" /> </script> <script type="text/ng-template" id="/template2.html"> <input ng-model="Ctr5.obj.num" /> </script>
var myApp4 = angular.module('myApp4',[]); myApp4.controller('myController5',function(){ this.string="50"; this.obj={num:11}; });
在打开这个html页面的时候遇到一个小插曲,chrome浏览器会报错,但是firefox就不会,看了错误信息(希望没说错)应该是chrome浏览器认为template1.html,template2.html和IncludeDemo.html是不同源的(javascript的同源策略),它找不到对应的template,firefox不会报错是因为firefox禁用掉了同源策略。这时如果非要用chrome也很简单,在本地使用一个服务器来访问IncludeDemo.html就可以了。比如node的http-server,python自带了一个简单服务器也可以解决这个问题。
在文件目录下python -m SimpleHTTPServer然后访问对应的html文件就可以了。
使用ng-transcode
ng-transcode可以达到同样的效果,但是需要自己写指令。
<div ng-app="myApp5">
<pane></pane>
</div>
var myApp5 = angular.module('myApp5',[]); myApp5.directive('pane',function(){ return{ restrict:"E", replace:true, templateUrl:'/template1.html' } });
对于ngtranscode还不是很熟悉,里面的参数有什么作用还不是很清楚,今天先写到这里,明天继续更新。