AngularOne AngularOne - 6 months ago 29
AngularJS Question

How to insert HTML element inside another HTML element in directive template?

I have a directive with simple template:

restrict: 'E',
link: function(scope, element, attrs) {},
template: '<ul></ul>


How can I add inside the template li elements dynamically with code in the link function?
My li list is HTML elements:

var newElement = $compile("<li><div>my text</div></li>")(scope);
element.append(newElement);


This will not add newElement as a child of ul...

Answer

element is not ul in your case but your directive wrapper element. You need to find list element first:

var newElement = $compile("<li><div>my text</div></li>")(scope);
element.find('ul').append(newElement);