Last week as I was creating a custom Angular directive, I noticed that the link function was no longer being called after I added a compile function to the directive’s definition.

I was surprised that I wasn’t able to find an answer to this issue after doing a quick Google search, but I finally found an answer.

When the compile function is defined on the directive, then it should return the link function. This also means there’s no need to define the link property on the directive’s definition.

So instead of looking like this:

angular.module('myModule', []).
  directive('myDriective', function() {
    return {
      compile: function(elem, attrs) {
        // compile code
      },
      link: function(scope, elem, attrs) {
        // link code
      }
    };
  });

It should look like this:

angular.module('myModule', []).
  directive('myDriective', function() {
    var linkFunction = function(scope, elem, attrs) {
      // link code
    };
    return {
      compile: function(elem, attrs) {
        // compile code
        return linkFunction;
      }
    };
  });

Navigation