Table Directive Headers
by Rob Rothe
HTML
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<div ng-app="app" class="container">
<div ng-controller="Controller as ctrl">
<my-table data="ctrl.data"></my-table>
</div>
</div>
CSS
body {
padding-top:20px;
}
JavaScript
angular
.module('app', [])
.controller('Controller', Controller)
.directive('myTable',myTable);
function Controller($location) {
var vm = this;
vm.data = [
{band_name:'Led Zeppelin',id:1},
{band_name:'The Pixies',id:2},
{band_name:'Beck',id:3}
];
}
function myTable() {
var directive = {
restrict: 'E',
template: '<table class="table"><tr><th ng-repeat="header in headers track by $index">{{header}}</th></tr><tr ng-repeat="d in data"><td>{{d.band_name}}</td><td>{{d.id}}</td</tr></table>',
scope: {
data: '='
},
link: link
};
return directive;
function link(scope,element,attr) {
scope.headers = [];
angular.forEach(scope.data,function(v,k) {
angular.forEach(scope.data[k],function(v2,k2) {
// replace underscors
k2 = k2.replace('_',' ');
// capitalize letters
k2 = k2.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
// get unique key names
if (scope.headers.indexOf(k2) === -1) {
scope.headers.push(k2);
}
});
});
}
}