0

All:

[UPDATE]: Got answer from this post(which takes time to read, so I just quote a simple answer of my understanding to that post here):

"Note that if you need a compile function and a link function (or pre and post link functions), the compile function must return the link function(s) because the 'link' attribute is ignored if the 'compile' attribute is defined."

I am pretty new to AngularJS directive, when I learn how to use $compile, I got one question, for example:

I can define a directive like:

app.directive("customdir", function(){
    return {
        restrict:"AE",
        compile: function(tmplEL, attrs){
            return function(scope, EL, attrs){/*this is the link function*/};
        },
        link: function(scope, EL, attrs){/*this is also the link function*/}
    }
})

My confusion here is: the compile function return a link function while we can define another link function in directive as well, are they same function or they are different function that the link: function(scope, EL, attrs) can override the link function returned from compile?

And what is the result if I defined both?

Thanks

Community
  • 1
  • 1
Kuan
  • 11,149
  • 23
  • 93
  • 201
  • 1
    http://stackoverflow.com/questions/12164138/what-is-the-difference-between-compile-and-link-function-in-angularjs – Kalhan.Toress Mar 23 '15 at 16:35
  • @K.Toress Thanks, that clear my confuse, I will update my post and add the straight answer to it. – Kuan Mar 23 '15 at 16:38
  • @K.Toress Could you help me with another question, I post here: http://stackoverflow.com/questions/29215947/what-happended-to-the-dom-node-when-angularjs-compile-a-directive – Kuan Mar 23 '15 at 17:00

1 Answers1

1

It's an "either/or".

You can define a compile property on the directive declaration object, which is a function that returns a link function/object - then the link property is ignored.

compile: function(tElement, tAttrs, transclude){
  return {
    pre: function prelink(){...},
    post: function postlink(){...}
  };
}

Or, since compile function is less commonly used, you could just specify the link property - which could be the post-link function (if it's a function value) or both pre-link and post-link, if it's an object value with these fields:

link: {
  pre: function prelink(scope, element, attrs, ctrls, transclude){
  },
  post: function postlink(scope, element, attrs, ctrls, transclude){
  }
}

Or simply:

link: function postlink(scope, element, attrs, ctrls, transclude){
}

More info in Angular docs

New Dev
  • 48,427
  • 12
  • 87
  • 129
  • Thanks for help. After reading the post, I finally figure out the relation between the link func returned from compile and the definition in directive attr. – Kuan Mar 23 '15 at 16:59