Angular Directives – compile & link & trusted HTML

More information on Angular directives:

Here’s a simple directive with a couple of scope variables that get displayed:

Here is the angular stuff:

Here is a fiddle for the example, which has some css and things. Nothing really special here.

Now, in order to make some DOM changes, we can’t change the element during the link function. If you want to change the element, you have to do it during the compile function. The compile function gets called when the directive is created, and should return the link function. This allows the directive to be modified. This example shows how to add a list to the directive.

We can also add some HTML with the “sce” module:

The interesting thing there is the compile function. The compile function gets the tElem, which is the template element itself. This function is run when the directive is compiled, and there is no scope available. We can, however, add some elements to the directive. Note that the compile function returns the link function.

Here is a working fiddle

Here’s a final fiddle showing how to add a list to the element’s div

Leave a Reply

Your email address will not be published. Required fields are marked *