directive如何在angular中使用?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
創新互聯建站服務項目包括洛隆網站建設、洛隆網站制作、洛隆網頁制作以及洛隆網絡營銷策劃等。多年來,我們專注于互聯網行業,利用自身積累的技術優勢、行業經驗、深度合作伙伴關系等,向廣大中小型企業、政府機構等提供互聯網行業的解決方案,洛隆網站推廣取得了明顯的社會效益與經濟效益。目前,我們服務的客戶以成都為中心已經輻射到洛隆省份的部分城市,未來相信會繼續擴大服務區域并繼續獲得客戶的支持與信任!
一、Directive的使用
angular.module("app",[]).directive("directiveName",function(){ return{ //通過設置項來定義 }; })
二、一個簡單的實例
html代碼:
js代碼:
var appModule = angular.module('helloApp', []); appModule.directive('hello', function() { return { restrict: 'E', template: 'Hello,friends!', replace: true }; });
效果截圖:
實例解析:
1、restrict:EACM的子集的字符串,它限制directive為指定的聲明方式。
E - 元素名稱:
A - 屬性名:
C - class名:
M - 注釋 :
2、默認情況下,directive將僅僅允許通過屬性聲明,ECA較常用。
template:指令顯示的模板內容,一般由html標簽和文本組成。通常情況下html內容較簡單的情況下使用,模板內容復雜的建議將公共部分抽離到html文件中,使用templateUrl屬性。
templateUrl - 與template基本一致,但模版通過指定的url進行加載。因為模版加載是異步的,所以compilation、linking都會暫停,等待加載完畢后再執行。
3、replace:如果設置為true,那么模版將會替換當前元素,而不是作為子元素添加到當前元素中。(注:為true時,模版必須有一個根節點)
上述實例dom節點截圖:
三、實例2:關于transclude
修改上面實例代碼:
{{myName}} var appModule = angular.module('helloApp', []); appModule.directive('hello', function() { return { restrict: 'E', template: 'Hello,my name is', replace: true, transclude:true }; });
效果截圖:
解析:
transclude:指令的作用是把我們自定義的語義化標簽替換成瀏覽器能夠認識的HTML標簽。上述例子replace設置為true,模版將會替換當前元素。而transclude設置為true的作用可以簡化地理解成:把
四、實例3:關于compile,link和controller
實例代碼:
phonecatDirectives.directive('exampleDirective', function() { return { restrict: 'E', template: 'Hello {{number}}!
', controller: function($scope, $element){ $scope.number = $scope.number + "22222 "; }, link: function(scope, el, attr) { scope.number = scope.number + "33333 "; }, compile: function(element, attributes) { return { pre: function preLink(scope, element, attributes) { scope.number = scope.number + "44444 "; }, post: function postLink(scope, element, attributes) { scope.number = scope.number + "55555 "; } }; } } }); //controller.js添加 dtControllers.controller('directive2',['$scope', function($scope) { $scope.number = '1111'; } ]); //html
運行結果:
Hello 1111 22222 44444 55555!
由結果可以看出來,controller先運行,compile后運行,link不運行。
將上例中的compile注釋掉的運行結果:
Hello 1111 22222 33333!
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注創新互聯行業資訊頻道,感謝您對創新互聯的支持。