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

1
  • I've succeded using jQuery.data() but I feel this is not "the angular way" Commented Jun 4, 2013 at 13:43

1 Answer 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
Sign up to request clarification or add additional context in comments.

3 Comments

thank you. I've tried to replicate the fiddle, but having two directives that should produce different output, if I do console.log(foo) in the linking function it outputs the last value twice, while in the compile function of course works fine... The weird thing is that a similar directive works in your fiddle.
do you call $compile(element)(scope) at any point? what's more, if you have nested directives it'll call first all the compile fn, then the links (your link fn is strictly a post-link function)
I was missing var foo!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.