Search code examples
javascriptangularjsangularjs-directiveangularjs-compile

AngularJS : How can I compile a directive as another directive?


I have Angular directives that compile

  1. <greeting /> to <print-greeting /> and

  2. <print-greeting /> to Hello World!

How can I put the greeting tag in my HTML and have it compile to print-greeting and then finally display Hello World!? It currently stops after turning it into print-greeting.

Here is my code: Plunker.


Directives copied from the above plunker:

greeting directive

// Transforms <greeting /> into <print-greeting />
app.directive("greeting", function ($compile) {
  return {
    restrict: 'E',
      priority: 2,
      compile: function ($templateElement, $templateAttributes) {

      var template = '<print-greeting />';
      $templateElement.replaceWith(template);

      return function LinkingFunction($scope, $element, $attrs) { };
    }
  };
});

print-greeting directive

// Transforms <print-greeting /> into "Hello World!"
app.directive("printGreeting", function ($compile) {
  return {
    restrict: 'E',
    priority: 1,
    compile: function ($templateElement, $templateAttributes) {
      var template = 'Hello World!';
       $templateElement.replaceWith(template);

       return function LinkingFunction($scope, $element, $attrs) { };
     }
  };
});

Solution

  • You are making a change to the already compiled template. In order to cause the secondary directive to get compiled, you need to recompile:

    return function LinkingFunction($scope, $element, $attrs) {
        $compile($element);
    };
    

    Fork of your Plunker