我们什么时候使用指令的编译函数的`preLink`? [英] When shall we use `preLink` of directive's compile function?

查看:30
本文介绍了我们什么时候使用指令的编译函数的`preLink`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

angularjs 指令的compile 函数有两个函数:preLinkpostLink.

The compile function of angularjs' directive has two functions: preLink and postLink.

在链接子元素之前执行.进行 DOM 转换是不安全的,因为编译器链接函数将无法找到正确的链接元素.

Pre-linking function

Executed before the child elements are linked. Not safe to do DOM transformation since the compiler linking function will fail to locate the correct elements for linking.

在子元素链接后执行.在 post-linking 函数中做 DOM 转换是安全的.

Executed after the child elements are linked. It is safe to do DOM transformation in the post-linking function.

它告诉我们在preLink中不应该做什么,我想知道我应该在什么时候使用preLink?大部分时间我只使用 postLink.有什么情况我们必须使用它吗?

It tells what we should not do in preLink, I wonder what and when should I use preLink? For most of time I just used postLink. Is there any case that we must use it?

推荐答案

您几乎不需要使用 preLink.可行的情况是当您需要在范围内操作数据时,但不是 DOMbefore link 函数(还有其他指令的)是执行.

You need almost never use preLink. Viable cases for it are when you need to manipulate data in scope, but not the DOM, before link functions (also of other directives) are executed.

正如 jacob 评论的那样,您也可以始终从控制器执行此操作,但有时将代码放在指令本身中更合适.

As jacob commented, you can always do that from a controller too, but sometimes it's more appropriate to have the code in the directive itself.

有一篇关于指令如何工作的优秀文章,其中对链接顺序进行了很好的解释:http://www.jvandemo.com/the-nitty-gritty-of-compile-and-link-functions-inside-angularjs-directives/

There is an excellent article about how directives work where linking order is explained well to: http://www.jvandemo.com/the-nitty-gritty-of-compile-and-link-functions-inside-angularjs-directives/

如果您需要一个很好的例子来说明为什么有时需要预链接,我建议您查看 angular 指令本身的代码.例如 https://github.com/angular/angular.js/blob/master/src/ng/directive/ngModel.js

If you need a good example of why pre-linking is sometimes necessary, I recommend you look at the code of angular directives themselves. For example https://github.com/angular/angular.js/blob/master/src/ng/directive/ngModel.js

这篇关于我们什么时候使用指令的编译函数的`preLink`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆