Can AngularJS directive pre-link and post-link functions be customized?

All we need is an easy explanation of the problem, so here it is.

I have seen many references to AngularJS pre- and post-link functions in literature about AngularJS.

I am not sure however whether these can be customized or are internal to the framework.

In other words, as an AngularJS developper, can I provide my own pre and post link functions to my custom directives?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Yes you can, as per @Mikke’s answer. To sum up, there are four ways to declare linking functions:

  1. From within compile specifying both preLink and postLink functions explicitly:

    compile: function compile(tElement, tAttrs, transclude) {
      return {
        pre: function preLink(scope, iElement, iAttrs, controller) { ... },
        post: function postLink(scope, iElement, iAttrs, controller) { ... }
      }
    }
    
  2. From within compile returning only postLink implicitly:

    compile: function compile(tElement, tAttrs, transclude) {
      return function postLink( ... ) { ... }
    }
    
  3. From within link specifying both preLink and postLink explicitly:

    link: {
      pre: function preLink(scope, iElement, iAttrs, controller) { ... },
      post: function postLink(scope, iElement, iAttrs, controller) { ... }
    }
    
  4. From withing link using postLink implicitly:

    link: function postLink( ... ) { ... }
    

Method 2

Yes, you can provide your own pre and post link functions. See the directive blueprint at Angular Docs’ Comprehensive Directive API.

{
    compile: function compile(tElement, tAttrs, transclude) {
        return {
            pre: function preLink(scope, iElement, iAttrs, controller) { ... },
            post: function postLink(scope, iElement, iAttrs, controller) { ... }
        }
        // or
        // return function postLink( ... ) { ... }
    },
}

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply