angularjs學習系(1),angularjs學習系
講述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:falsereplace: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