Make It Dynamic

Next, imagine the otcDynamic directive can’t use a static template. The directive needs to look at some boolean flags, user data, or service information, and dynamically construct the template markup. In the following example, we’ll only simulate this scenario. We are still using a static string, but we’ll pretend we created the string dynamically and use element.html to place the markup into the DOM.

The above sample no longer functions correctly and will only render a button displaying the literal text {{label}} to a user.

Markup has to go through a compilation phase for Angular to find and activate directives like ng-click and {{label}}.

Compilation

The $compile service is the service to use for compilation. Invoking $compile against markup will produce a function you can use to bind the markup against a particular scope (what Angular calls a linking function). After linking, you’ll have DOM elements you can place into the browser.