Search code examples
angularjsangular-directive

What is the equivalent of returning an object with only a post-link function?


In the Angular JS documentation for $compile it is stated:

A compile function can have a return value which can be either a function or an object.

returning a (post-link) function - is equivalent to registering the linking function via the link property of the config object when the compile function is empty.

returning an object with function(s) registered via pre and post properties - allows you to control when a linking function should be called during the linking phase. See info about pre-linking and post-linking functions below.

Based on The nitty-gritty of compile and link functions inside AngularJS directives as an example of a compile function returning an object:

function createDirective(name){  
  return function(){
    return {
      restrict: 'E',
      compile: function(tElem, tAttrs){
        console.log(name + ': compile');
        return {
          post: function(scope, iElem, iAttrs){
            console.log(name + ': post link');
          }
        }
      }
    }
  }
}

My interpretation of the documentation is that returning a function is allowed and it's assumed to be a the post-link function, i.e. the following is equivalent:

function createDirective(name){  
      return function() {
        return {
          restrict: 'E',
          compile: function(tElem, tAttrs){
            console.log(name + ': compile');
            return function(scope, iElem, iAttrs){
                console.log(name + ': post link');
              }
          }
        }
      }
    }

Is this correct?


Solution

  • According to the definition provided, this would be the equivalent:

    function createDirective(name){  
        return function() {
            return {
                restrict: 'E',
                link: function(scope, element, attrs){
    
                }
            }
        }
    }
    

    As stated in the definition, returning post link is same as link only when compile is empty... so there is link property above. You can see that the function signature is even same, just different variable names.