Angular JS – $compile to dynamically generate a template

There are situations (for example on testing, or when we have a directive whose template needs to be dynamically generated from the values we pass to it) in which we need to manually apply a template to the DOM and to manually compile it, in order to have the binding between its markup and our scope. This can be done with the $compile module, that is the same Angular uses internally to apply the directives. In this example we are creating a directive that dynamically defines its template.

angular.module("myApp.directives").directive("myDirective", ["$compile", function ($compile) {
    return {
        restrict: "E",
        scope: {
            myId: "@",
            myTitle: "@"
        },
        link: function (scope, element) {
 
            //Here we are dynamically generating the template
            var template = "<h1 id='" + scope.myId + "'>{{myTitle}}</h1>";
 
            //Here we are manually compiling a dynamic template by inserting
            //it within our directive and by applying our scope over it 
            element.html(template);
            $compile(element.contents())(scope);
        }
    }
}]);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s