AngularJS指令:链接和编译功能是否可以协同工作?

jvi*_*tti 35 angularjs angularjs-directive

我对这个功能有些怀疑.

可以说我有这个指令:

.directive('hello', function () {
    return {
      template: '<div>Hello <span ng-transclude></span></div>',
      restrict: 'E',
      transclude: true,
      compile: function() {
        console.log('Compile()');

        return {
          pre: function() {
            console.log('PreLink()');
          },
          post: function() {
            console.log('PostLink()');
          }
        };
      },
      link: function postLink(scope, element, attrs) {
        console.log('Link()');
      }
    };
  }
Run Code Online (Sandbox Code Playgroud)

我将它添加到我的模板中:

<hello>World</hello>
Run Code Online (Sandbox Code Playgroud)

控制台日志:

Compile()
PreLink()
PostLink()
Run Code Online (Sandbox Code Playgroud)

那么为什么link()不被称为?

如果不是从compile()我返回一个对象,而是返回一个打印PreLink()控制台日志的函数:

Compile()
PreLink()
Run Code Online (Sandbox Code Playgroud)

如果我没有从Compile()控制台日志返回任何内容:

Compile()
Run Code Online (Sandbox Code Playgroud)

仍然link()没有被召唤.

如果我只是评论Compile()那么Link()最后打印:

Link()
Run Code Online (Sandbox Code Playgroud)

有人可以解释这一切吗?是Link()Compile()意味着一起工作?我应该只使用Compile PreLink()PostLink()

Ed *_*ffe 83

link并且compile不在一起工作,没有.

在指令定义对象中,如果您定义link,那就像在compile函数中使用preLink带有代码的空函数的空函数的简写postLink.一旦定义compile,link就会被angular忽略,因为compile应该返回链接函数.

如果您只返回一个函数compile,那么它将在链接执行.

或者换句话说,link只是postLink在链接范围之后调用的函数的快捷方式compile.

这是(有点)记录在这里 - 查看代码示例中的注释.

  • "因为编译应该返回链接函数" - 正是我正在寻找的信息.谢谢! (8认同)

Jur*_*uri 11

几天前,Jurgen Van de Moere发表了一篇很好的文章,题目是"AngularJS指令中编译和链接函数的细节".它解释很清楚的责任和顺序compile,pre-linkpost-link功能.

http://www.jvandemo.com/content/images/2014/Aug/cycle-2.png

你一定要看一下:http://www.jvandemo.com/the-nitty-gritty-of-compile-and-link-functions-inside-angularjs-directives