Dynamically add directives in AngularJS
Hacking my way to glory
by dbouwman
HTML
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.18/angular.min.js"></script>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<section ng-app="myApp" ng-controller="MainCtrl">
<h1>Dynamically Add Directives</h1>
<!-- <input type="text" ng-model="greeting"> -->
<div id="space-for-buttons"></div>
<button od-block-adder class="btn btn-default" x-blocks="header.blocks" >Add Block</button>
<!-- block viewer will watch the header.blocks array and render items as they are added -->
<div class="container">
<div od-block-viewer id="block-container" class="container" x-blocks="header.blocks">Yar</div>
</div>
<pre>
{{header | json}}
</pre>
</section>
CSS
section{
padding: 2em;
}
button{
padding:0.3em;
margin: 0.3em;
}
.od-block{
min-height:150px;
width:90%;
border: 1px solid #CCC;
margin:10px;
}
JavaScript
var myApp = angular.module('myApp', []);
function MainCtrl($scope) {
$scope.count = 0;
$scope.greeting = 'Y HALO THAR PEEPS OV EARTH';
$scope.header = {
blocks:[
{
name:'block 1',
directive:'od-img-text',
blockData:[
{
odImgBlock: {
url:'http://placekitten.com/400/150',
alt:'all the kitteh',
title: 'mai kitteh'
}
},
{
odTextBlock:{
md: '### Markdown'
}
}
]
},{
name:'block 2',
directive:'od-three-up',
blockData: [
[
{
odImgBlock:{
url:'http://placekitten.com/300/200',
alt:'all the kitteh',
title: 'mai kitteh'
}
},{
odTextBlock:{
md: '### Markdown'
}
}
],
[
{
odImgBlock:{
url:'http://placekitten.com/300/200',
alt:'all the kitteh',
title: 'mai kitteh'
}
},{
odTextBlock:{
md: 'Second box'
}
}
],
[
{
odImgBlock:{
url:'http://placekitten.com/300/200',
alt:'all the kitteh',
title: 'mai kitteh'
}
},{
odTextBlock:{
md: 'This is different'
}
}
]
]
}
]
};
}
// BlockAdder: clicking adds a block, and the layout updates
myApp.directive("odBlockAdder",function(){
return {
scope: {
blockContainerId: '@container',
blocks: '=blocks'
},
restrict: 'A',
link: function(scope,element, attrs){
//on-click...
element.bind("click", function(){
console.log('blocks in blockAdder: ' +...