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

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

问题描述

编译 angularjs'指令的功能有两个功能: $ P $砰砰 postLink

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.

执行后的子元素联系在一起。它是安全的DOM转型后链接功能。

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

它告诉我们不应该在 $ P $砰砰做的,我不知道什么时候我应该使用 $ P $砰砰?对于大多数的时候我只是用 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?

推荐答案

您需要几乎从来不使用 $ P $砰砰。可行的情况下,它是当你需要操作范围的数据,而不是DOM 链接函数(还有其他指令)被执行。

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.

雅各评论,你总是可以做到这一点从控制器太多,但有时它在指令本身的code是比较合适的。

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.

有大约指令的工作原理,其中连接顺序很好地解释了一个很好的文章:<一href=\"http://www.jvandemo.com/the-nitty-gritty-of-compile-and-link-functions-inside-angularjs-directives/\" rel=\"nofollow\">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/

如果你需要的,为什么pre联有时是必要的一个很好的例子,我建议你看一下角度指令本身的code。例如 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天全站免登陆