標籤:
AngularJS提供了一系列的內建指令,如ng開頭的指令,同時AngularJS也允許使用者自訂指令。
目錄:
1.自訂指令
2.使用自訂指令
3.自訂指令的內嵌使用
自訂指令
AngularJS中使用directive()方法來自訂指令,directive() 方法可以接受兩個參數:
name(字元):指令的名字,用來在視圖中引用特定的指令
factory_function(函數):這個函數返回一個對象,其中定義了指令的全部行為
例如:建立一個test指令:
var app = angular.module(‘myApp‘,[]); app.directive(‘hello‘,function(){ return { restrict:‘AECM‘, template:‘<div>hello world</div>‘, replace:true }; });
說明:
在directive方法的第二個函數參數中,返回了一個對象,欄位的意義如下:
restrice:定義了標籤的使用方法,一共四種,分別是AECM
template:定義標籤的模板。裡面是用於替換自訂標籤的字串
repalce:是否替換
另外還有transclude:標識是否嵌套
使用自訂指令
指令在html中的使用有4中方法,分別對應restrice的標籤的4個使用方法AECM
A:屬性
<div hello></div>--------><div>hello world</div>
E:元素
<hello></hello>--------><div hello="">hello world</div>
C:樣式(class的值)
<div class="hello"></div>------><div class="hello">hello world</div>
M:注釋
<!-- directive:hello ----------->各個版本不一樣
自訂指令的內嵌使用
app.directive(‘test‘,function(){ return { restrict:‘AECM‘, template:‘<div>hello <div ng-transclude></div> world</div>‘, transclude:true };});
說明:自訂指令的內嵌使用需要將transclude欄位賦值為true,template中使用ng-transclude來確定內嵌的位置。
執行個體代碼如下:
<!DOCTYPE><html ng-app="myApp"><head> <meta charset="utf-8" /> <script src="https://code.angularjs.org/1.3.1/angular.min.js"> </script></head><body> <div>0</div> <hello></hello> <div>1</div> <div hello></div> <div>2</div> <div class="hello"></div> <div>3</div> <!-- directive:hello --> <div>4</div> <hello>3333</hello> <div>5</div> <test>4444</test> <script type="text/javascript"> var app = angular.module(‘myApp‘,[]); app.directive(‘hello‘,function(){ return { restrict:‘AECM‘, template:‘<div>hello world</div>‘, replace:true }; }); app.directive(‘test‘,function(){ return { restrict:‘AECM‘, template:‘<div>hello <div ng-transclude></div> world</div>‘, transclude:true }; }); </script></body></html>
AnngularJS---自訂指令