標籤:return angular 注意 -- 元素 ack html 添加 ict
建立自訂的指令
除了 AngularJS 內建的指令外,我們還可以建立自訂指令。
你可以使用 .directive 函數來添加自訂的指令。
要調用自訂指令,HTML 元素上需要添加自訂指令名。
使用駝峰法來命名一個指令, myAngular, 但在使用它時需要以 - 分割, my-angular:
你可以通過以下方式來調用指令:
元素名
<!DOCTYPE html><html><head> <meta charset="utf-8"> <script src="angular-1.6.3/angular.js"></script></head><body><div ng-app="myDirective"> <my-angular></my-angular></div><script> var app=angular.module("myDirective",[]); app.directive("myAngular", function() {//注意名稱myAngular---<my-angular> return { template : "<p>自訂指令!</p>" }; });</script></body></html>屬性:
<!DOCTYPE html><html><head><meta charset="utf-8"><script src="https://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script> </head><body ng-app="myApp"><div runoob-directive></div><script>var app = angular.module("myApp", []);app.directive("runoobDirective", function() { return { template : "<h1>自訂指令!</h1>" };});</script></body></html>類名:
<!DOCTYPE html><html><head><meta charset="utf-8"><script src="https://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script> </head><body ng-app="myApp"><div class="runoob-directive"></div><script>var app = angular.module("myApp", []);app.directive("runoobDirective", function() { return { restrict : "C", template : "<h1>自訂指令!</h1>" };});</script><p><strong>注意:</strong> 你必須設定 <b>restrict</b> 的值為 "C" 才能通過類名來調用指令。</p></body></html>注釋:
<!DOCTYPE html><html><head><meta charset="utf-8"><script src="https://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script> </head><body ng-app="myApp"><!-- directive: runoob-directive --><script>var app = angular.module("myApp", []);app.directive("runoobDirective", function() { return { restrict : "M", replace : true, template : "<h1>自訂指令!</h1>" };});</script><p><strong>注意:</strong> 我們需要在該執行個體添加 <strong>replace</strong> 屬性, 否則評論是不可見的。</p><p><strong>注意:</strong> 你必須設定 <b>restrict</b> 的值為 "M" 才能通過注釋來調用指令。</p></body></html>限制使用
你可以限制你的指令只能通過特定的方式來調用。
restrict 值可以是以下幾種:
E 作為元素名使用
A 作為屬性使用
C 作為類名使用
M 作為注釋使用
restrict 預設值為 EA, 即可以通過元素名和屬性名稱來調用指令。
AngularJS學習篇(三)