【问题标题】:how to pass data from compile to linking function in angularjs?如何将数据从编译传递到angularjs中的链接函数?
【发布时间】:2013-06-04 13:38:59
【问题描述】:

我在指令的compile函数中根据DOM元素做了一些计算。我需要将结果存储在作用域中,所以我试图将此数据传递给链接函数(它可以访问作用域),但我不知道该怎么做。

我需要在 compile 函数中执行这些计算,因为我需要在 DOM 元素被其他指令的链接函数处理之前访问它们(使用指令优先级)。

【问题讨论】:

  • 我已经成功使用 jQuery.data() 但我觉得这不是“角度方式”

标签: angularjs angularjs-directive


【解决方案1】:

我认为考虑到 JavaScript 符号的范围就足够了。看到这个http://jsfiddle.net/JV7vH/1/

你定义了一个编译函数,它必须返回一个链接函数。因为它是一个内部函数,所以来自父函数的符号是​​可见的。

app.directive('ui',function ($compile) {
  return {
    restrict:'E',
    template: '<div class="mcb">hey</div>',
    compile: function ($tElement, $tAttrs) {
        var foo = "a valuable value";
        console.log('compiling' + foo);
        return function (scope, element, attrs) {
            console.log('linking:' + foo);
        }
    }  
  }
});

您可能还想了解order of execution of compile-link @joshdavidmiller 说:

<div directive1>
  <div directive2>
    <!-- ... -->
  </div>
</div>

执行顺序是

directive1: compile
  directive2: compile
directive1: controller
directive1: pre-link
  directive2: controller
  directive2: pre-link
  directive2: post-link
directive1: post-link

【讨论】:

  • 谢谢。我试图复制小提琴,但是有两个应该产生不同输出的指令,如果我在链接函数中执行 console.log(foo) 它输出最后一个值两次,而在编译函数中当然可以正常工作.. . 奇怪的是,一个类似的指令在你的小提琴中起作用。
  • 你在任何时候都会调用 $compile(element)(scope) 吗?更重要的是,如果你有嵌套指令,它会首先调用所有编译 fn,然后是链接(你的链接 fn 严格来说是一个链接后函数)
  • 我错过了 var foo!
猜你喜欢
  • 1970-01-01
  • 2011-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-07
  • 2019-10-05
相关资源
最近更新 更多