寫在前面:directive 是 AngularJS 中的重中之重,因此會分多篇講解。本章主要介紹 directive 回傳物件裡幾個較基礎的屬性。
AngularJS 使用 .directive() 來定義指令,該方法接收兩個參數:name(指令名稱)與 factory_function(定義指令全部行為、回傳一個物件的函式)。
例子:
//index.js angular.module('myApp',[]); myApp.directive('myDirective',function() {return {};});
回傳的物件包含以下屬性與方法:
1:restrict:String
用來說明 myDirective 指令在 DOM 中以何種形式被聲明(也就是在 html 裡該把它用在什麼地方)。可選值有:E(元素)、A(屬性,預設值)、C(類名)、M(註解),可單獨使用也可組合使用。有一種說法是:若想自訂一個獨立功能的指令,即它能独立完成一連串操作、不依附其他元素或屬性,就定義為元素;若想用它來擴展某個已存在指令的功能,則定義為屬性。這種理解未必完全嚴謹,但確實是個不錯的選擇標準。
2:priority:Number
用來定義指令的優先級(預設為 0,ngRepeat 是所有內建指令中優先級最高的,為 1000),優先級高的先執行。
3:terminal:Boolean
與 priority 有一定關聯,用來判斷是否停止執行當前元素上比本指令優先級更低的指令,但相同優先級的仍會執行。例子:
//index.js angular.module('myApp',[]) .directive('myDirective',function() { return { restrict: 'AE', priority: 1, template: '<div>hello world</div>' }; }) .directive('myDirective1',function() { return { restrict: 'AE', priority: 3, terminal: true }; })
<!-- index.html --> <div my-directive my-directive1></div>
若沒有定義 myDirective1,瀏覽器會顯示 hello world;但加上 myDirective1、並把它的 priority 設得比 myDirective 大、同時把 terminal 設為 true 之後,myDirective 就會被停止執行。
4:template:String/Function
用來定義一個模板(使用到該指令的 html 部分會被替換成該模板內容,所以模板主要是 html 格式)。有兩種形式:一段 html 文字,或一個回傳模板字串的函式,後者接收 tElement、tAttrs 兩個參數。
5:templateUrl:String/Function
當模板內容較多時,直接嵌在 template 裡會顯得冗餘,可以將模板程式碼另外存成一個檔案,這時就需要 templateUrl。它也有兩種形式:一個代表外部 html 檔案路徑的字串,或一個回傳外部路徑字串的函式,後者同樣接收 tElement、tAttrs 兩個參數。
6:replace:Boolean
預設為 false,用來指明模板是被當成子元素插入到調用該指令的元素內部,還是直接覆蓋取代該元素。例子:
//index.js angular.module('myApp',[]) .directive('myDirective',function() { return { restrict: 'A', template: '<div>hello world</div>', replace: true/false }; })
<!-- index.html --> <my-directive></my-directive>
當 replace 為 false 時,瀏覽器端呈現為 <my-directive><div>hello world</div></my-directive>;為 true 時則呈現為 <div>hello world</div>。
7:transclude:Boolean
例子:
<!-- index.html --> <div my-directive>world</div>
像這個例子,若指令內部有內容,一般情況下 template 會直接覆蓋掉該內容;但如果你想把它保留下來,這時 transclude 就派上用場了。
//index.js angular.module('myApp',[]) .dirctive('myDirective',function() { return { restrict: 'EA', transclude: true, template: '<div>hello <span ng-transclude></span></div>' }; })
上面的程式碼會把 html 中指令內的 world 內嵌到模板的 span 元素裡。要特別注意,span 元素加上了 ng-transclude 這個內建指令屬性(這點很重要)。總之,這個屬性的作用是告訴 AngularJS 編譯器:把它從 DOM 元素中取得的內容,放到它發現 ng-transclude 指令的位置。以上就是本文的全部內容,希望對你的學習有所幫助。