PCoelho PCoelho - 4 months ago 49
AngularJS Question

Dynamically add directive in AngularJS

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

I have a simple

. 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
. 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'
$( 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:


You have a lot of pointless jQuery in there, but the $compile service is actually super simple in this case:

.directive( 'test', function ( $compile ) {
  return {
    restrict: 'E',
    scope: { text: '@' },
    template: '<p ng-click="add()">{{text}}</p>',
    controller: function ( $scope, $element ) {
      $scope.add = function () {
        var el = $compile( "<test text='n'></test>" )( $scope );
        $element.parent().append( el );

You'll notice I refactored your directive too in order to follow some best practices. Let me know if you have questions about any of those.