AngularJS 指令 : Are Link and Compile functions meant to work together?

标签 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()');
      }
    };
  }

我将它添加到我的模板中:
<hello>World</hello>

控制台日志:
Compile()
PreLink()
PostLink()

那么为什么是link()不被叫?

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

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

link()没有被调用。

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

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

最佳答案

linkcompile不一起工作,不。

在指令定义对象中,如果你只有定义 link ,这就像有一个空 compile 的简写函数为空 preLink使用您在 postLink 中的代码运行功能。只要您定义 compile , link被 angular 忽略,因为 compile 应该返回链接函数。

如果你只从 compile 返回一个函数,然后它会被执行 发帖 关联。

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

它(有点)记录在案 here - 查看代码示例中的注释。

关于AngularJS 指令 : Are Link and Compile functions meant to work together?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19797419/

相关文章:

javascript - Angular : How to update controller scope associated to directive scope's object as it changes?

javascript - 在纯 html 中插入 AngularJS 指令(ng-click)

angularjs - 检查后执行指令

javascript - Angular JS 将字符串数组传递给指令

javascript - Angular Directive(指令)中模板的路径?

javascript - 基于属性的两个数组之间的不同对象 - lodash

javascript - 在 Angular JS 指令中检索 css 值

javascript - AngularJS Controller 在第一次刷新页面后不起作用

javascript - AngularJS:面板和内部链接上的 ui-sref

javascript - angularJS $http get 中的可选参数