3 回答

TA貢獻1818條經驗 獲得超8個贊
編譯:
這是Angular實際編譯指令的階段。對于給定指令的每個引用,只調用一次此編譯函數。例如,假設您正在使用ng-repeat指令。ng-repeat必須查找它所附加的元素,提取它所附加的html片段并創建模板函數。
如果您使用過HandleBars,下劃線模板或等效模板,就像編譯模板以提取模板函數一樣。對于此模板函數,您傳遞數據,該函數的返回值是html,數據位于正確的位置。
編譯階段是Angular中返回模板函數的步驟。角度中的此模板函數稱為鏈接函數。
鏈接階段:
鏈接階段是將數據($ scope)附加到鏈接函數的位置,它應該返回鏈接的html。由于該指令還指定了這個html的去向或更改的內容,因此它已經很好了。這是您要對鏈接的html進行更改的功能,即已經附加了數據的html。在角度中如果你在鏈接函數中編寫代碼,它通常是post-link函數(默認情況下)。它是一種在鏈接函數將數據與模板鏈接后調用的回調。
控制器:
控制器是您放置某些指令特定邏輯的地方。這個邏輯也可以進入鏈接函數,但是你必須將該邏輯放在范圍上以使其“可共享”。問題在于,您將使用指令來破壞范圍,而這些東西實際上并不是預期的。那么,如果兩個指令希望彼此交談/相互合作,那么又有什么選擇呢?當然,您可以將所有邏輯放入服務中,然后使這兩個指令依賴于該服務,但這只會帶來一個依賴性。另一種方法是為這個范圍提供一個控制器(通常是隔離范圍?),然后當該指令“需要”另一個指令時,該控制器被注入另一個指令。

TA貢獻1799條經驗 獲得超9個贊
A directive
允許您以聲明方式擴展HTML詞匯表以構建Web組件。該ng-app
屬性是一個指令,所以是ng-controller
所有的ng- prefixed attributes
。指令可以是attributes
,tags
甚至class
names
是comments
。
指令如何誕生(compilation
和instantiation
)
編譯:我們將在呈現之前將該compile
函數用于manipulate
DOM并返回一個link
函數(將為我們處理鏈接)。這也是放置任何需要與所有instances
this指令共享的方法的地方。
link:我們將使用該link
函數注冊特定DOM元素上的所有偵聽器(從模板克隆)并設置我們對頁面的綁定。
如果設置在compile()
函數中,它們只會被設置一次(這通常是你想要的)。如果在link()
函數中設置,則每次將HTML元素綁定到對象中的數據時都會設置它們。
<div ng-repeat="i in [0,1,2]"> <simple> <div>Inner content</div> </simple></div>app.directive("simple", function(){ return { restrict: "EA", transclude:true, template:"<div>{{label}}<div ng-transclude></div></div>", compile: function(element, attributes){ return { pre: function(scope, element, attributes, controller, transcludeFn){ }, post: function(scope, element, attributes, controller, transcludeFn){ } } }, controller: function($scope){ } }; });
Compile
函數返回pre
和post
鏈接函數。在預鏈接函數中,我們有實例模板以及范圍controller
,但是模板沒有綁定到范圍,仍然沒有被轉換的內容。
Post
link function是post link是最后一個執行的函數?,F在transclusion
已經完成了the template is linked to a scope
,和view will update with data bound values after the next digest cycle
。該link
選項只是設置post-link
功能的快捷方式。
controller:指令控制器可以傳遞給另一個指令鏈接/編譯階段。它可以作為在指令間通信中使用的手段注入其他指南。
您必須指定所需指令的名稱 - 它應綁定到同一元素或其父元素。該名稱可以帶有以下前綴:
? – Will not raise any error if a mentioned directive does not exist.^ – Will look for the directive on parent elements, if not available on the same element.
使用方括號[‘directive1′, ‘directive2′, ‘directive3′]
需要多個指令控制器。
var app = angular.module('app', []);app.controller('MainCtrl', function($scope, $element) {});app.directive('parentDirective', function() { return { restrict: 'E', template: '<child-directive></child-directive>', controller: function($scope, $element){ this.variable = "Hi Vinothbabu" } }});app.directive('childDirective', function() { return { restrict: 'E', template: '<h1>I am child</h1>', replace: true, require: '^parentDirective', link: function($scope, $element, attr, parentDirectCtrl){ //you now have access to parentDirectCtrl.variable } }});
- 3 回答
- 0 關注
- 572 瀏覽
添加回答
舉報