1.replace——最簡單的使用方法,直接將自定義標籤替換爲模板內的內容: javascript
html:css
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 <script type="text/javascript" src="angular.js" ></script> 7 <script type="text/javascript" src="template.js" ></script> 8 </head> 9 <body ng-app="app"> 10 <template></template> 11 </body> 12 </html>
javascipt:html
1 var app=angular.module("app",[]) 2 app.directive("template",function(){ 3 return { 4 restrict: 'E', 5 template: '<div>Hi template</div>', 6 replace: true 7 } 8 })
2. transclude(變換)——將自定義標籤替換成咱們所編寫的HTML模板,可是自定義標籤內部的內容會保留在具備ng-transclude指令的標籤內:java
html:app
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 <script type="text/javascript" src="angular.js" ></script> 7 <script type="text/javascript" src="template.js" ></script> 8 </head> 9 <body ng-app="app"> 10 <hello> 11 <br> 12 <span>使用transclude,自定義標籤內部的內容會被保留在模板標籤中具備ng-transclude指令的標籤內部</span> 13 </hello> 14 <hello></hello> 15 </body> 16 </html>
javascript:函數
1 var appModule = angular.module('app', []); 2 appModule.directive('hello', function() { 3 return { 4 restrict: 'E', 5 template: '<div>Hi there <span ng-transclude>這裏的內容不會顯示,只會顯示自定義標籤內部的內容</span></div>', 6 transclude: true 7 }; 8 });
3. link函數——綁定事件到元素上,一個簡單的典型的插件就能實現了spa
css:插件
1 .expander { 2 border: 1px solid black; 3 width: 250px; 4 } 5 6 .expander>.title { 7 background-color: black; 8 color: white; 9 padding: .1em .3em; 10 cursor: pointer; 11 } 12 13 .expander>.body { 14 padding: .1em .3em; 15 }
html:rest
1 var app=angular.module("app",[]) 2 app.directive("temp",function(){ 3 return { 4 restrict : "EA", 5 replace : true, 6 transclude : true, 7 scope : { 8 title : '=tempTitle' 9 }, 10 template : '<div>' 11 + '<div class="title" ng-click="toggle()">{{title}}</div>' 12 + '<div class="body" ng-transclude ng-show="showMe"></div>' 13 + '</div>', 14 link : function(scope,element,attrs){ 15 scope.showMe=false; 16 scope.toggle=function(){ 17 scope.showMe=!scope.showMe 18 } 19 } 20 } 21 }) 22 23 app.controller("tempCtrl",function($scope){ 24 $scope.title="點我,你能看到更多" 25 $scope.text="是否是多了幾個字" 26 })
html:code
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <script type="text/javascript" src="angular.js" ></script> 6 <script type="text/javascript" src="temp.js"></script> 7 <title></title> 8 </head> 9 <body ng-app="app"> 10 <div ng-controller="tempCtrl"> 11 <temp class="expander" temp-title="title">{{text}}</temp> 12 </div> 13 </body> 14 </html>