I'm going to expand your question a bit and also include the compile function.(我将扩大您的问题,并包括编译功能。)
compile function - use for template DOM manipulation (ie, manipulation of tElement = template element), hence manipulations that apply to all DOM clones of the template associated with the directive.(编译功能 -用于模板 DOM操纵(即,tElement =模板元素的操纵),因此适用于与指令关联的模板的所有DOM克隆的操纵。)
(If you also need a link function (or pre and post link functions), and you defined a compile function, the compile function must return the link function(s) because the 'link'
attribute is ignored if the 'compile'
attribute is defined.)((如果您还需要一个链接功能(或前,后链接功能),你定义一个编译函数,编译函数必须返回链接功能(S),因为'link'
属性将被忽略,如果'compile'
属性定义。))
link function - normally use for registering listener callbacks (ie, $watch
expressions on the scope) as well as updating the DOM (ie, manipulation of iElement = individual instance element).(链接功能 -通常用于注册侦听器回调(即,作用域上的$watch
表达式)以及更新DOM(即,对iElement =单个实例元素的操作)。)
It is executed after the template has been cloned.(克隆模板后执行。) Eg, inside an <li ng-repeat...>
, the link function is executed after the <li>
template (tElement) has been cloned (into an iElement) for that particular <li>
element.(例如,在<li ng-repeat...>
,已经为特定的<li>
元素克隆了<li>
模板(tElement)(将其插入到iElement中)之后,将执行链接功能。) A $watch
allows a directive to be notified of scope property changes (a scope is associated with each instance), which allows the directive to render an updated instance value to the DOM.($watch
允许指令通知范围属性更改(范围与每个实例相关联),这允许指令将更新后的实例值呈现给DOM。)
controller function - must be used when another directive needs to interact with this directive.(控制器功能 -当另一个指令需要与此指令进行交互时,必须使用它。)
Eg, on the AngularJS home page, the pane directive needs to add itself to the scope maintained by the tabs directive, hence the tabs directive needs to define a controller method (think API) that the pane directive can access/call.(例如,在AngularJS主页上,窗格指令需要将自身添加到tabs指令所维护的范围内,因此tabs指令需要定义一个可以访问/调用该窗格指令的控制器方法(think API)。)
For a more in-depth explanation of the tabs and pane directives, and why the tabs directive creates a function on its controller using this
(rather than on $scope
), please see 'this' vs $scope in AngularJS controllers .(有关选项卡和窗格指令的更深入说明,以及为什么选项卡指令使用this
指令(而不是在$scope
)在其控制器上创建函数,请参见AngularJS控制器中的“ this”与$ scope 。)
In general, you can put methods, $watches
, etc. into either the directive's controller or link function.(通常,您可以将方法, $watches
等放入指令的控制器或链接函数中。)
The controller will run first, which sometimes matters (see this fiddle which logs when the ctrl and link functions run with two nested directives).(控制器将首先运行,这有时很重要(请参见该小提琴 ,该日志记录了ctrl和link函数使用两个嵌套指令运行的时间)。) As Josh mentioned in a comment , you may want to put scope-manipulation functions inside a controller just for consistency with the rest of the framework.(正如Josh在评论中提到的那样,您可能希望将范围操作功能放在控制器内,只是为了与框架的其余部分保持一致。) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…