How can I dynamically add a directive in AngularJS?

I have a very boiled down version of what I am doing that gets the problem across.

I have a simple directive. Whenever you click an element, it adds another one. However, it needs to be compiled first in order to render it correctly.

My research led me to $compile. But all the examples use a complicated structure that I don’t really know how to apply here.

Fiddles are here: http://jsfiddle.net/paulocoelho/fBjbP/1/

And the JS is here:

var module = angular.module('testApp', [])
    .directive('test', function () {
    return {
        restrict: 'E',
        template: '<p>{{text}}</p>',
        scope: {
            text: '@text'
        },
        link:function(scope,element){
            $( element ).click(function(){
                // TODO: This does not do what it's supposed to :(
                $(this).parent().append("<test text="n"></test>");
            });
        }
    };
});

Solution by Josh David Miller:
http://jsfiddle.net/paulocoelho/fBjbP/2/

7 Answers
7

Leave a Comment