指令基础
> How to declare the various functions?
> What is the difference between a source template and an instance template?
> In which order the directive functions are executed?
> What else happens between these function calls?
函数性质,do和dont的
> Compile
> Controller
> Pre-link
> Post-link
相关问题:
> Directive: link vs compile vs controller。
> Difference between the ‘controller’,‘link’ and ‘compile’ functions when defining an angular.js directive。
> What is the difference between compile and link function in angularjs。
> Difference between the pre-compile and post-compile element in AngularJS directives?。
> Angular JS Directive – Template,compile or link?。
> post link vs pre link in Angular js directives。
对于单个指令
<body> <div log='some-div'></div> </body>
使用以下指令声明:
myApp.directive('log',function() { return { controller: function( $scope,$element,$attrs,$transclude ) { console.log( $attrs.log + ' (controller)' ); },compile: function compile( tElement,tAttributes ) { console.log( tAttributes.log + ' (compile)' ); return { pre: function preLink( scope,element,attributes ) { console.log( attributes.log + ' (pre-link)' ); },post: function postLink( scope,attributes ) { console.log( attributes.log + ' (post-link)' ); } }; } }; });
控制台输出将是:
some-div (compile) some-div (controller) some-div (pre-link) some-div (post-link)
我们可以看到编译首先执行,然后控制器,然后预链接和最后是后链接。
嵌套指令
Note: The following does not apply to directives that render their children in their link function. Quite a few Angular directives do so (like ngIf,ngRepeat,or any directive with
transclude
). These directives will natively have theirlink
function called before their child directivescompile
is called.
原始HTML标记通常由嵌套元素组成,每个元素都有自己的指令。如下面的标记(见plunk):
<body> <div log='parent'> <div log='..first-child'></div> <div log='..second-child'></div> </div> </body>
控制台输出将如下所示:
// The compile phase parent (compile) ..first-child (compile) ..second-child (compile) // The link phase parent (controller) parent (pre-link) ..first-child (controller) ..first-child (pre-link) ..first-child (post-link) ..second-child (controller) ..second-child (pre-link) ..second-child (post-link) parent (post-link)
我们可以在这里区分两个阶段 – 编译阶段和链接阶段。
编译阶段
当加载DOM时,Angular开始编译阶段,从上到下遍历标记,并在所有指令上调用compile。图形上,我们可以这样表示:
也许重要的是,在这个阶段,编译函数获取的模板是源模板(而不是实例模板)。
链接阶段
DOM实例通常只是将源模板呈现给DOM的结果,但它们可以通过ng-repeat创建,或者即时引入。
每当具有指令的元素的新实例被呈现给DOM时,链接阶段就开始。