講述angularjs創建指令replace,transclude域的用法
angularjs的指令創建有四種形式,比如創建的指令hello:
(1)頁面標籤的形式E:
<hello>
<div>angularjs創建指令</div>
<div>replace的用法</div>
</hello>
(2)標籤屬性的形式A(angularjs默認的):<div hello></div>
(3)標籤樣式類的形式C:<div class="hello"></div>
(4)頁面註釋的形式M: <!-- directive:hello -->(註釋號前後有個空格)
指令的創建代碼:
myApp.directive('hello',function(){
return {
restrict:'ACEM',
template:'<div>hello everyone!</div>',
//transclude:false
replace:false
}
});
【一】如果replace設置爲false,最終頁面展現的html結果如下:
C: <div class="hello"><div>hello everyone!</div></div>
A: <div hello=""><div>hello everyone!</div></div>
E: <hello><div>hello everyone!</div></hello>
M: <!-- directive:hello -->(沒有效果,無效的)
【二】如果replace設置爲true,最終頁面展現的html結果如下: C:<div class="hello">hello everyone!</div>
A:<div hello="">hello everyone!</div>
E:<div>hello everyone!</div>
M:<div hello="">hello everyone!</div> (有效)
使用replace有個什麼缺點呢,比如我要把文章開頭指令hello下的<div>angularjs創建指令</div> <div>replace的用法</div>要顯示在頁面上,replace是辦不到的,這個可以用transclude域的設置來解決:
myApp.directive('hello',function(){
return {
restrict:'ACEM',
template:'<div>hello everyone!<span ng-transclude></span></div>',
transclude:true
}
});
這樣就可以把指令內的DOM標籤展現出來:
C:<div class="hello"><div>hello everyone!<span ng-transclude=""><span class="ng-scope">樣式類</span></span></div></div>
A:<div hello=""><div>hello everyone!<span ng-transclude=""><span class="ng-scope">屬性</span></span></div></div>
E:<hello><div>hello everyone!<span ng-transclude="">
<div class="ng-scope">angularjs創建指令</div>
<div class="ng-scope">replace的用法</div>
</span></div></hello>
M:<!-- directive:hello -->
參考:http://stackoverflow.com/questions/15285635/how-to-use-replace-of-directive-definition