是什么在指令2“postLink”功能之间的区别?(What's the differenc

2019-07-18 21:01发布

从angularjs的文档,定义一个指令的时候,有一个postLinkcompilepostLinklink

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;
});

什么是它们之间的区别? 我注意到postLinklink有一个参数小于一个中compile 。 以及是否有任何其他的区别吗?

Answer 1:

他们没有什么不同,你有什么有从文档只是伪代码。 该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
           }
         }
      }
   };
});

...你只需要一个。



Answer 2:

主要差别是,在预链接功能,子元素尚未相连。 但在链接功能后,它有。

这对DOM操作的影响。 由于连接还可以操作DOM的过程,它是唯一安全的指令操作DOM时,其子已关联 - 这是唯一真正在链接后功能。



文章来源: What's the difference between the 2 “postLink” functions in directive?