如何将数据从编译传递到angularjs中的链接函数?

Ant*_*nna 2 angularjs angularjs-directive

我在指令的编译函数中基于DOM元素进行一些计算.我需要将结果存储在作用域中,所以我试图将这些数据传递给链接函数(可以访问作用域),但我不知道该怎么做.

我需要在编译函数中执行这些计算,因为我需要访问DOM元素,然后才能通过其他指令的链接函数(使用指令优先级)处理它们.

Edu*_*nal 5

考虑到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);
        }
    }  
  }
});
Run Code Online (Sandbox Code Playgroud)

您可能还想了解一下编译链接的执行顺序 @joshdavidmiller说给出:

<div directive1>
  <div directive2>
    <!-- ... -->
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

执行的顺序是

directive1: compile
  directive2: compile
directive1: controller
directive1: pre-link
  directive2: controller
  directive2: pre-link
  directive2: post-link
directive1: post-link
Run Code Online (Sandbox Code Playgroud)