指令比较糊涂,今天查了查,首先上代码吧(程序员 coding and think deeply);
<!DOCTYPE html> <html lang="en" ng-app='myApp'> <head> <meta charset="UTF-8"> <title>Document</title> <script type="text/javascript" src='angular.min.js'></script> </head> <body> <div ng-controller='firstController'> {{name}} <exp-directive></exp-directive> </div> <script type="text/javascript"> var app = angular.module('myApp',[]); app.controller('firstController',['$scope',function($scope){ $scope.name = 'controller name'; console.log('moule controller') }]) app.directive('expDirective',function(){ return { restrict:'AE', template:'<p>hello {{name}} </p>', replace: true, compile: function(){ console.log('complie start') return { pre: function preLink(scope, element, attributes) { console.log("pre directive "); }, post: function postLink(scope, element, attributes) { console.log("linker directive") ; } } }, link: function(scope){ console.log('derictive link') }, controller: function($scope){ $scope.name = 'directive controller name' console.log('dertive controller') } } }) </script> </body> </html>
浏览器: directive controller name
hello directive controller name
控制台(console.log):
complie start
moule controller
dertive controller
pre directive
linker directive
从浏览器看directive controller污染了 module controller 内的内容,所有尽量少用controller,用link,一般用在需要require,指令之间的调用时用到(这个是在网上看到未验证);
从控制台来说
1. 当有complie 时link是不起作用的,注释complie之后link才会起作用。
2.complie编译时编译之前的,之后编译module controller的内容,再编译directive内容( controller 优先级大于 link)。
最后我把最终的编译顺序按自己理解的写一遍
ng-app -- ng-controller -- directive指令 -- complie编译 -- complie start -- module controller -- directive controller (如果没有complie, directive link 在 directive controller 后面)
我有一个猜测:
complie里可能有directive controller的回调函数,并且在pre 和 post之前,而link不执行说明link是complie的一部分,不存在回调;
声明个人想法不一定全对:有错误的话,多谢指正;