11

angularjs のドキュメントから、ディレクティブを定義するときに、postLinkincompilepostLinkin がありますlink

myModule.directive('directiveName', function factory(injectables) {
  var directiveDefinitionObject = {
    priority: 0,
    template: '<div></div>',
    templateUrl: 'directive.html',
    replace: false,
    transclude: false,
    restrict: 'A',
    scope: false,
    compile: function compile(tElement, tAttrs, transclude) {
      return {
        pre: function preLink(scope, iElement, iAttrs, controller) { ... },
        post: function postLink(scope, iElement, iAttrs, controller) { ... }
      }
    },
    link: function postLink(scope, iElement, iAttrs) { ... }
  };
  return directiveDefinitionObject;
});

それらの違いは何ですか?postLinkinlinkの引数が の引数より少ないことに気付きましたcompile。また、他に違いはありますか?

4

2 に答える 2

30

それらは違いはありません。あなたが持っているのは、ドキュメントの疑似コードだけです。postLink 関数は最も重要な関数であるため、さまざまな方法で宣言できます。

例としてプランカーを次に示します...

... そして、postLink 関数のさまざまな宣言を示す疑似コードを次に示します。

app.directive('dir1', function () {
   return function(scope, elem, attr) {
       //this is the same
   };
});

app.directive('dir2', function () {
   return {
       link: function(scope, elem, attr) {
           //this is the same
       }
   };
});

app.directive('dir3', function () {
   return {
      compile: function compile(tElement, tAttrs, transclude) {
         return {
           post: function postLink(scope, elem, attrs) {
              //this is the same
           }
         }
      }
   };
});

... 必要なのは 1 つだけです。

于 2013-01-28T15:20:34.130 に答える