Dynamically adding Angular directives to the DOM with $compile

One of the most useful talents of frameworks like Angular is the ability to create rich and dynamic applications. Being able to build directives that can dynamically spawn additional directives, allows for highly configurable, configuration driven pages that can take your applications to the next level. By using $compile, this becomes an easy 3 step process.

The basic idea is very simple: 1) you build up the markup for the directive that you need, including any attributes (great for passing data into the directive), 2) you compile the markup with the current scope, and 3) finally you insert it into the DOM. The first part should be fairly straightforward. You can even generate the tag name on the fly since it is just a string. Next, you use the $compile service (don't forget to inject it!) with this format: $compile(markupString)(currentScope). Finally, append the output to the DOM with your favorite option (jQuery, jqLite, D3, etc). See the code below or this plunker for a very simple sample directive that implements this concept.

  angular.module('dynamicDirectives', [])
    .directive('directiveGenerator', directiveGenerator);

    directiveGenerator.$inject = ['$compile'];

    function directiveGenerator($compile) {
      var directive = {
        restrict: 'E',
        scope: {},
        link: linkFunc

      function linkFunc(scope, element){
        scope.checked = true;
        scope.someText = 'some text';
        scope.someNumber = 5;

        var markupToAppend = [
          '<input type="checkbox" ng-model="checked"/>',
          '<input type="text" ng-model="someText"/>',
          '<input type="number" ng-model="someNumber"/>'];



      return directive;
AngularJavaScriptquick tips