angularjs – 角度指令 – 何时和如何使用编译,控制器,预链接和
当编写一个Angular伪指令时,可以使用下面的函数来操作声明该伪指令的元素的DOM行为,内容和外观:
>编译 似乎有一些混乱,因为应该使用哪个函数。这个问题包括: 指令基础 > How to declare the various functions? 函数性质,do和dont的 > Compile 相关问题: > Directive: link vs compile vs controller。
执行指令函数的顺序是什么?
对于单个指令 基于以下plunk,请考虑以下HTML标记: <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) 我们可以看到编译首先执行,然后控制器,然后预链接和最后是后链接。 嵌套指令
原始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时,链接阶段就开始。 在这个阶段,Angular调用控制器,预链接,迭代孩子,并在所有指令上调用post-link,像这样: (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |