我有一个html文件a.html,如下:
<div>
a.html
</div>
我想利用angularjs在a.html嵌入另外一个b.html,如下:
<div>
b.html
</div>
希望的结果如下:
<div>
a.html
<div>
b.html
</div>
</div>
请问如何实现?
<div>
a.html
<bhtml></bhtml>
</div>
angular
.module('app')
.directive('bhtml',function(){
return {
templateUrl:'/b.html',
restrict:'E',
replace:true
}
})
这个差不多可以做到lz想要的效果了。但是比较麻烦一点,简单点的办法会多一个标签:
<div>
a.html
<div ng-include="/b.html"></div>
</div>
结果:
<div>
a.html
<div ng-include="/b.html">
<div>
b.html
</div>
</div>
</div>
a.html
<div>
hello a
<dv ng-include="b.html"></div>
</div>
b.html
<div>
hello b
</div>
ui-router
ng-include..
ng-include
简单, 但是,要实现复杂结构比较困难ng-transcode
灵活,容易实现复杂的HTML结构,但是要单独写directive
(指令)
angular.module('transclude', [])
.directive('pane', function(){
return {
restrict: 'E',
transclude: true,
scope: { title:'@' },
template: '<div style="border: 1px solid black;">' +
'<div style="background-color: gray">{{title}}</div>' +
'<div ng-transclude></div>' +
'</div>'
};
});
代码'<div ng-transclude></div>'
相当于一个插入点, 类似Web组件规范中的插入点概念.
当你在模版中的HTML元素上使用 <pane>
这个指令的时候, <pane>
中的内容可以被插入到ng-transcode
定义的位置
例如:
<pane title="{{title}}">{{text}}</pane>
另外,如果你不想在指令中拼接模版字符串, 你可以使用templateUrl
替代template
细节请参考: http://angular.duapp.com/api/ng.directive:ngTransclude
set transclued: true
in your directive, and put transclude
in your directive template where you want to embed another html template