Dynamically add directives in AngularJS
For a walkthrough see http://blog.fourtonfish.com/post/74055065673/dynamically-add-directives-in-angularjs-no-jquery
HTML
<section ng-app="myApp" ng-controller="MainCtrl">
<addbuttonsbutton></addbuttonsbutton>
<div id="space-for-buttons"></div>
</section>
CSS
section {
padding: 2em;
}
button {
padding:0.3em;
margin: 0.3em;
}
JavaScript
var myApp = angular.module('myApp', []);
function MainCtrl($scope) {
$scope.count = 0;
}
myApp.directive("addbuttonsbutton", function () {
return {
restrict: "E",
template: "<button addbuttons>Click to add buttons</button>"
}
});
//Directive for adding buttons on click that show an alert on click
myApp.directive("addbuttons", function ($compile) {
return function (scope, element, attrs) {
element.bind("click", function () {
scope.count++;
angular.element(document.getElementById('space-for-buttons'))
.append($compile("<alert alert='count'></alert>")(scope));
});
};
});
//Directive for showing an alert on click
myApp.directive("alert", function () {
return {
template: "<div><button class='btn btn-default'>Show alert # {{count}}</button></div>",
scope: {
a: '@alert'
},
replace:true,
link: function (scope, element, attrs) {
element.bind("click", function () {
console.log(scope.a);
alert("This is alert #" + scope.a);
});
}
};
});