angularJS中directive应该是最重要最强大的了,在ddo中,有两个地方可以引入自定义的功能,一个是controller属性,一个是link属性,directive的这两个属性到底有什么区别呢?我们的代码到底应该放到directive的controller还是link属性中去呢?
问一下自己:我希望这段代码什么时间点去运行呢?对这个问题的回答决定了你应该讲代码放到哪里:
- 在compilation之前运行? - 放到controller属性中去
- 希望暴露一个API给其他directives? -放到controller属性中去定义API
- 在compilation之后运行? - 放到link属性中
angular在compile,link,controller被编译的时间顺序:
angular.module('compilation', [])
.directive('logCompile', function($rootScope) {
$rootScope.log = "";
return {
controller: function($scope, $attrs) {
$rootScope.log = $rootScope.log + ($attrs.logCompile + ' (controller)\n');
},
compile: function compile(element, attributes) {
$rootScope.log = $rootScope.log + (attributes.logCompile + ' (compile)\n');
return {
pre: function preLink(scope, element, attributes) {
$rootScope.log = $rootScope.log + (attributes.logCompile + ' (pre-link)\n');
},
post: function postLink(scope, element, attributes) {
element.prepend(attributes.logCompile);
$rootScope.log = $rootScope.log + (attributes.logCompile + ' (post-link)\n');
}
};
}
};
})
.directive('terminate', function() {
return {
terminal: true
};
});
http://jasonmore.net/angular-js-directives-difference-controller-link/