angularjs指令(directive)中的controller,compile,link函数有什
今天我们来一起了解一下它们有什么不同的地方: var ag = angular.module("myApp",[]); ag.controller("myCtrl",["$rootScope",function($rootScope){ }]); ag.directive("order",function(){ return{ restrict:"AE",controller:function($scope,$element,$attrs,$transclude) { console.log("controller"); },compile:function(tElement,tAttrs,transclude){ console.log("compile"); return{ pre:function(scope,iElement,iAttrs,controller){ console.log("pre") },post:function(scope,controller){ console.log("post") } } },link:function(scope,controller){ console.log("link") } } }); 我们可以看到什么order指令中写了controller,complie,link函数;我们可以思考一下上面会输出一下什么来. 从上面的输出结果我们可以得出两个结论:
首先我们来解释第一个问题;看下图(摘自stackoverflow.com) 从图中我们可以看到整个 AngularJs 的生命周期;分为两个阶段:
ag.directive("order",function(){ return{ restrict:"AE",compile:function(tELe,transcludeFn){ //进行编译后的dom操作 return{ pre:function(scope,controller){ // 在子元素被链接之前执行 // 在这里进行Dom转换不安全 },controller){ // 在子元素被链接之后执行 } } } } })
var ag = angular.module("myApp",controller){ console.log("link") } } }); 上面指令执行时;会输出: 我们可以看到controller函数先执行,然后是link函数.但是链接阶段会执行controller,link函数;那么他们有什么不同;我们在什么情况该用哪个? 答案是:
实际使用的一些建议:
到这里:我们应该有一点了解这三者有什么差异了吧?其实这个问题考的就是我们对AngularJs生命周期的了解. 最后我们用一个实际例子来看一下AngularJs的生命周期: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body ng-app="myApp" ng-controller="myCtrl"> <div parent> <div child></div> </div> <script src="../plugins/angularjs/angular.src.js"></script> <script> var ag = angular.module("myApp",function($rootScope){ }]); ag.directive("parent",$transclude) { console.log("parent controller"); },transclude){ console.log("parent compile"); return{ pre:function(scope,controller){ console.log("parent pre") },controller){ console.log("parent post") } } } } }); ag.directive("child",function(){ return{ restrict:"AE",$transclude) { console.log("child controller"); },transclude){ console.log("child compile"); return{ pre:function(scope,controller){ console.log("child pre") },controller){ console.log("child post") } } } } }); </script> </body> </html> 结果如图: 可以参照上面的angularjs生命周期图来理解. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |