Gary Gary -5 years ago 99
AngularJS Question

Unable to compile a dynamically added Directive into a page

I am trying to add a dynamically added element directive into a page but it is not working and getting compiled in the page it is added. Here is the plunker code. What is wrong with the code?

<!DOCTYPE html>
<html ng-app="myApp">
<script src=""></script>
var app = angular.module('myApp', []);
$scope.xx = ['x','c','y','z','a'];
$scope.add = function(){
var templ = document.getElementById('test').innerHTML;
templ = templ+'<datan-type content="test1" con="{{xx}}"></datan-type>';
document.getElementById('test').innerHTML = templ;

app.directive('datanType', function ($compile) {
return {
restrict: 'E',
replace: true,
link: function (scope, ele, attrs) {
var testTemplate1 = '<h1 ng-repeat="x in arr">Test{{x}}</h1>';
var testTemplate2 = '<h1>Test2</h1>';
var testTemplate3 = '<h1>Test3</h1>';
var template = '';
scope.arr = eval(attrs.con);
case 'test1':
template = testTemplate1;
case 'test2':
template = testTemplate2;
case 'test3':
template = testTemplate3;



<meta charset="utf-8">
<title>JS Bin</title>
<body ng-controller="fCtrl">
<datan-type content="test1" con="{{xx}}"></datan-type>
<div id="test"></div>
<button ng-click="add()">Add Form Elem Eg - Error Area</button>

Answer Source

Gary, this was killing me so I made it my morning goal to figure out the silly syntax:

Working Plnkr - Clicky

Change your controller code to :

var elementToAdd = angular.element('<datan-type content="test1" con="{{xx}}"></datan-type>');

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download