angularJS directive中的controller和link function辨析

在angularJS中,你有一系列的view,负责将数据渲染给用户;你有一些controller,负责管理$scope(view model)并且暴露相关behavior(通过$scope定义)给到view;你有一些directive,负责将user interaction和$scope behavious link起来。但是还有一样东西: a directive controller.这个directive controller子一个directive的context中定义,但是它又可以被injected到其他的directives中作为一种便利化inter-directive communication的方法。

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/