Dynamically add directives in AngularJS
For a walkthrough see http://blog.fourtonfish.com/post/74055065673/dynamically-add-directives-in-angularjs-no-jquery
HTML
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.js"></script>
<section ng-app="myApp" ng-controller="MainCtrl">
<button add-directive>Create dynamic directive</button>
</section>
<div>
<div id="dirContainer"></div>
</div>
CSS
section {
padding: 2em;
}
button {
padding:0.3em;
margin: 0.3em;
}
.dynadir{
background-color:hotpink;
padding:10px;
color:#ffffff;
}
JavaScript
var myApp = angular.module('myApp', []);
function MainCtrl($scope) {
$scope.data = {
id: 666,
name: "Fabruce"
}
}
// Directive for compiling a dynamic directive
myApp.directive("addDirective", function ($http, $compile) {
return function (scope, element, attrs) {
element.bind("click", function () {
var mockData = "json=" + encodeURI(JSON.stringify(scope.data));
var httpRequest = $http({
method: 'POST',
url: '/echo/json/',
data: mockData
})
// compiles dynamic directive
.success(function (data, status) {
debugger;
console.log('json', scope.data);
angular.element(document.getElementById('dirContainer')).append($compile("<my-dynamic-directive name='data.name' data='data'></my-dynamic-directive>")(scope));
});
});
};
});
// The Dynamic directive
myApp.directive("myDynamicDirective", function () {
return {
restrict: "E",
scope: {
data: "=",
name: "="
},
template: "<div class='dynadir'><div>hello {{name}}</div>"+
"<div>hello {{data.name}} </div></div>",
link: function (scope, element, attr) {
console.log("The data passed: %O", scope.data); // <- undefined why?
}
}
});