Page 103 - AngularJS权威教程
P. 103
10.3 绑定策略 83
为这个侧边栏创建一个简单的指令,并将transclude参数设置为true: 1
angular.module('myApp', [])
.directive('sidebox', function() {
return { 2
restrict: 'EA',
scope: {
title: '@' 3
},
transclude: true,
template: '<div class="sidebox">\
<div class="content">\ 4
<h2 class="header">{{ title }}</h2>\
<span class="content" ng-transclude>\
</span>\ 5
</div>\
</div>'
};
}); 6
这段代码告诉AngularJS编译器,将它从DOM元素中获取的内容放到它发现ng-transclude
指令的地方。 7
借助transclusion,我们可以将指令复用到第二个元素上,而无须担心样式和布局的一致
性问题。 8
例如,下面的代码会产生两个样式完全一致的侧边栏,效果如图10-2所示。
9
<div sideboxtitle="Links">
<ul>
<li>First link</li> 10
<li>Second link</li>
</ul>
</div>
<div sideboxtitle="TagCloud"> 11
<div class="tagcloud">
<a href="">Graphics</a>
<a href="">AngularJS</a> 12
<a href="">D3</a>
<a href="">Front-end</a>
<a href="">Startup</a>
</div> 13
</div>
14
15
16
17
图10-2 侧边栏 18