加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

AngularJS指令:链接和编译功能是否意味着一起工作?

发布时间:2020-12-17 08:42:03 所属栏目:安全 来源:网络整理
导读:我对这个功能有一些疑问。 让我说我有这个指令: .directive('hello',function () { return { template: 'divHello span ng-transclude/span/div',restrict: 'E',transclude: true,compile: function() { console.log('Compile()'); return { pre: function(
我对这个功能有一些疑问。

让我说我有这个指令:

.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()

仍未链接()。

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

Link()

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

链接和编译不一起工作,没有。

在指令定义对象中,如果你只定义链接,这就像在postLink函数中使用一个带有空的preLink函数的空编译函数和你的代码的速记。一旦你定义了编译,链接被角度忽略,因为编译应该返回链接函数。

如果你只从编译返回一个函数,那么它将被执行post link。

或者,换句话说,链接只是postLink函数的一个快捷方式,在scope通过编译链接后被调用。

它是(类型)记录here – 看看代码示例中的注释。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读