指令中2个"postLink"函数之间有什么区别?

Fre*_*ind 11 angularjs angularjs-directive

从angularjs的文档中,在定义一个指令时,有一个postLinkin compile和一个postLinkinlink

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;
});
Run Code Online (Sandbox Code Playgroud)

他们之间有什么区别?我注意到postLinkin link的参数小于in 中的参数compile.还有其他区别吗?

Ben*_*esh 30

它们没有什么不同,你所拥有的只是来自文档的伪代码.postLink函数是最重要的函数,因此有多种方法可以声明它.

这是一个以Plunker为例......

...这里有一些伪代码,显示了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
           }
         }
      }
   };
});
Run Code Online (Sandbox Code Playgroud)

......你只需要一个.