0

What does the $compile function do and how can we use it to add a directive dynamically via js code?

Does anyone have fully functioning code samples?

Danial Lokman
  • 131
  • 1
  • 5
  • http://stackoverflow.com/questions/24615103/angular-directives-when-and-how-to-use-compile-controller-pre-link-and-post – Sanjeev Singh Mar 15 '15 at 18:56

1 Answers1

0

Thought it will help a lot of developers out there to get something fully functioning on this. Here's a sample answer.

The $compile service compiles the fragment of html(<test text="n"></test>) that includes the directive("test" as an element) and produces a function. This function can then be executed with a scope to get the "html output from a directive".

var compileFunction = $compile("<test text="n"></test>");
var HtmlOutputFromDirective = compileFunction($scope);

More details with full code samples here: http://www.learn-angularjs-apps-projects.com/AngularJs/dynamically-add-directives-in-angularjs

Ogglas
  • 62,132
  • 37
  • 328
  • 418
Danial Lokman
  • 131
  • 1
  • 5