您好,欢迎访问一九零五行业门户网

聊聊angular指令中的preLink和postLink函数

本篇文章给大家介绍一下angular指令中的prelink和postlink函数。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。
【相关推荐:《angular教程》】
指令模板选项有complie和link两个字段,两者之间存在如下关系:
当compile字段存在时,link字段将被忽略,compile函数的返回值将作为link字段。
当compile不存在,link字段存在时,angular通过这样directive.compile = valuefn(directive.link);包装一层,使用用户定义的link字段。
而link分为prelink和postlink两个阶段,从link字段或者compile函数的返回值来看:
如果是函数,那么这样的link,会被认为是postlink。
如果是对象,那么link.pre作为prelink函数,link.post作为postlink函数。app.directive('mydirective', function () { return { compile: function () { return { pre: function () { console.log('prelink'); }, post: function () { console.log('postlink'); } } } }});
我们的指令工厂返回的是一个函数,那么angular通过这样的包装 directive = { compile: valuefn(directive) },即该函数将作为指令对象的postlink函数,像这样:
app.directive('mydirective', function () { return function () { console.log('postlink'); }});
angular编译链接指令的顺序为了看清angular编译链接指令的顺序,用以下代码输出日志的方式来说明:
<body ng-app="myapp"> <a a1> <b b1 b2></b> <c> <e e1></e> <f> <g></g> </f> </c> <d d1></d> </a></body> var app = angular.module('myapp', []);var names = ['a1', 'b1', 'b2', 'e1', 'd1']; names.foreach(function (name) { app.directive(name, function () { return { compile: function () { console.log(name + ' compile'); return { pre: function () { console.log(name + ' prelink'); }, post: function () { console.log(name + ' postlink'); } }; } }; });});
输出:
a1 compileb1 compileb2 compilee1 compiled1 compilea1 prelinkb1 prelinkb2 prelinkb2 postlinkb1 postlinke1 prelinke1 postlinkd1 prelinkd1 postlinka1 postlink
可以看出:
所有的指令都是先compile,然后prelink,然后postlink。
节点指令的prelink是在所有子节点指令prelink,postlink之前,所以一般这里就可以通过scope给子节点传递一定的信息。
节点指令的postlink是在所有子节点指令prelink,postlink完毕之后,也就意味着,当父节点指令执行postlink时,子节点postlink已经都完成了,此时子dom树已经稳定,所以我们大部分dom操作,访问子节点都在这个阶段。
指令在link的过程,其实是一个深度优先遍历的过程,postlink的执行其实是一个回溯的过程。
节点上的可能有若干指令,在搜集的时候就会按一定顺序排列(通过bypriority排序),执行的时候,prelinks是正序执行,而postlinks则是倒序执行。
明白了这些以后,就要小心一些容易忽略的陷阱。
<body ng-app="myapp"> <my-parent></my-parent></body> var app = angular.module('myapp', []); app.directive('myparent', function () { return { restrict: 'ea', template: '<div>{{greeting}}{{name}}'+ '<my-child></my-child>'+ '</div>', link: function(scope,elem,attr){ scope.name = 'lovesueee'; scope.greeting = 'hey, i am '; } };});app.directive('mychild', function () { return { restrict: 'ea', template: '<div>{{says}}</div>', link: function(scope,elem,attr){ scope.says = 'hey, i am child, and my parent is ' + scope.name; } };});
结果子指令输出为undefined
hey, i am lovesueeehey, i am child, and my parent is undefined
由上可以,myparent指令的link是一个postlink函数,而这个函数将在mychild指令的prelink和postlink执行完之后才执行。所以scope.name = undefined。
更多编程相关知识,请访问:编程入门!!
以上就是聊聊angular指令中的prelink和postlink函数的详细内容。
其它类似信息

推荐信息