1.命名:
可以使用普通字符串,也可以使用駝峯法來命名一個指令,例如 firstDirective, 但在使用它時需要以 - 分割: first-directive。
2.創建方式:
Angularjs的指令創建有四種形式,比如創建的指令hello:
(1)元素名(E):
<hello></hello>
(2)標籤屬性(默認)(A):
<div hello></div>
(3)標籤樣式類的形式(C):
<div class="hello"></div>
(4)註釋(M)(註釋號注意有個空格):
<!-- directive: hello -->
3.指令的創建JS代碼:
myApp.directive('hello',function(){
return {
restrict:'AE',
template:'<div>hello everyone!</div>',
//transclude:false
replace:false
}
});
a.restrict 值可以是以下幾種:
-
E
作爲元素名使用,A
作爲屬性使用,C
作爲類名使用,M
作爲註釋使用
restrict 默認值爲 EA
, 即可以通過元素名和屬性名來調用指令。
b.replace 解析
初始 html:
E: <hello><div>angular指令學習</div></hello>
如果replace設置爲false,最終頁面展現的html結果如下:
E: <hello><div>hello everyone!</div></hello>
如果replace設置爲true,原有 dom 節點被覆蓋,最終頁面展現的html結果如下: E:<div>hello everyone!</div>
c.如果想把html 裏原有的DOM 結構保留,要設置transclude的值,並利用 ng-transclude 保存原有 html:
myApp.directive('hello',function(){
return {
restrict:'ACEM',
template:'<div>hello everyone!<div ng-transclude></div></div>', //通過ng-transclude,將默認的 HTML 保存在div標籤裏
transclude:true
}
});
HTML 如下顯示:(原有的 html 得以保留)
E:<hello><div>hello everyone!<div ng-transclude><div class="ng-scope">angular 指令學習</div></div></hello>
transclude這個配置很重要,可以實現指令的互相嵌套。
參考:①:http://stackoverflow.com/questions/15285635/how-to-use-replace-of-directive-definition
②: http://www.runoob.com/angularjs/angularjs-directives.html