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/

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM