Directive到底是個怎麼樣的一個東西呢?我我的的理解是這樣的:將一段html、js封裝在一塊兒,造成一個可複用的獨立個體,具體特定的功能。下面咱們來詳細解讀一下Directive的通常性用法。html
var myDirective = angular.module('directives', []);
myDirective.directive('directiveName', function($inject) {
return {
template: '<div></div>',
replace: false,
transclude: true,
restrict: 'E',
scope: {},
controller: function($scope, $element) {
},
complie: function(tElement, tAttrs, transclude) {
return {
pre: function preLink(scope, iElement, iAttrs, controller) {
},
post: function postLink(scope, iElement, iAttrs, controller) {
}
};
},
link: function(scope, iElement, iAttrs) {
}
};
});
這裏直接return了一個object,對象中包括比較多的屬性,這些屬性都是對自定義directive的定義。
name
priority
teminal
true
,則表示當前的priority將會成爲最後一組執行的directive,即比此directive的priority更低的directive將不會執行。同優先級依然會執行,可是順序不肯定。scope
true
{}
controller
$scope
與當前元素結合的scope$element
當前的元素$attrs
當前元素的屬性對象$transclude
一個預先綁定到當前scope的轉置linking functionrequire
?
不要拋出異常。這將使得這個依賴變爲一個可選項^
容許查找父元素的controllerrestrict
E
元素名稱:A
屬性名:
C
class名:
M
註釋:template
replace
爲true,則將模版內容替換當前的html元素,並將原來元素的屬性、class一併轉移;若是replace
爲false,則將模版元素看成當前元素的子元素處理。templateUrl
replace
transclude
ngTransclude
使用。transclusion的有點是linking function可以獲得一個預先與當前scope綁定的transclusion function。通常地,創建一個widget,建立獨立scope,transclusion不是子級的,而是獨立scope的兄弟級。這將使得widget擁有私有的狀態,transclusion會被綁定到父級scope中。(上面那段話沒看懂。但實際實驗中,若是經過調用myDirective,而transclude設置爲true或者字符串且template中包含的時候,將會將的編譯結果插入到sometag的內容中。若是any的內容沒有被標籤包裹,那麼結果sometag中將會多了一個span。若是原本有其餘東西包裹的話,將維持原狀。但若是transclude設置爲’element’的話,any的總體內容會出如今sometag中,且被p包裹)
compile
link
參考地址:http://blog.gejiawen.com/2014/07/16/usage-for-angularjs-directive/
先上指令的模板。能夠看出,指令包含一個輸入框一個下拉選擇框。

指令的邏輯部分:

參考地址:http://blog.gejiawen.com/2015/12/20/using-ng-model-controller-with-angular-directive/?utm_source=tuicool&utm_medium=referral