angularjs指令中的compile与link函数详解(4)


/**
    * Compile function
    *
    * @param tElem - template element
    * @param tAttrs - attributes of the template element
    */
    function(tElem, tAttrs){

// ...

};

Pre-link 函数

使用pre-link函数可以运行一些业务代码在ng执行完compile函数之后,但是在它所有子指令的post-link函数将要执行之前.

scope对象以及element实例将会做为参数传递给pre-link函数:

下面是函数样子:

复制代码 代码如下:


/**
    * Pre-link function
    *
    * @param scope - scope associated with this istance
    * @param iElem - instance element
    * @param iAttrs - attributes of the instance element
    */
    function(scope, iElem, iAttrs){

// ...

};

Post-link 函数

使用post-link函数来执行业务逻辑,在这个阶段,它已经知道它所有的子指令已经编译完成并且pre-link以及post-link函数已经执行完成.

这就是被认为是最安全以及默认的编写业务逻辑代码的原因.

scope实例以及element实例做为参数传递给post-link函数:

下面是函数样子:

复制代码 代码如下:


/**
    * Post-link function
    *
    * @param scope - scope associated with this istance
    * @param iElem - instance element
    * @param iAttrs - attributes of the instance element
    */
    function(scope, iElem, iAttrs){

// ...

};

总结

现在你应该对compile,pre-link,post-link这此函数之间的区别有了清晰的认识了吧.

如果还没有的话,并且你是一个认真的ng开发者,那么我强烈建议你重新把这篇文章读一读直到你了解为止

理解这些概念非常重要,能够帮助你理解ng原生指令的工作原理,也能帮你优化你自己的自定义指令.

如果还有问题的话,欢迎大家在下面评论里加上你的问题

以后还会接着分析关于指令里的其它两个问题:

1.指令使用transclusion属性是怎么工作的?
2.指令的controller函数是怎么关联的

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgsygx.html