2

I do some calculations based on DOM elements in the compile function of a directive. I need to store the result in the scope, so I was trying to pass this data to the linking function (which has access to the scope), but I don't know how to do it.

I need to perform these calculations in the compile function since I need to access DOM elements before they are processed by the linking function of other directives (using directive priority).

4

1 回答 1

5

I think it's enough considering the scope of JavaScript symbols. See this http://jsfiddle.net/JV7vH/1/

you define a compile function that has to return a link function. because it's an inner function, symbols from parent functions are visible.

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);
        }
    }  
  }
});

you might also want to read about the order of execution of compile-link @joshdavidmiller said that given:

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

the order of execution is

directive1: compile
  directive2: compile
directive1: controller
directive1: pre-link
  directive2: controller
  directive2: pre-link
  directive2: post-link
directive1: post-link
于 2013-06-04T13:47:32.187 回答