angularJS directive中的controller和link function辨析

世有因果知因求果發表於2015-10-01

在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/

 

相關文章