AngularJS inner directive attributes
http://stackoverflow.com/q/26448040/415057
by codef0rmer
HTML
<script src="https://code.angularjs.org/snapshot/angular.js"></script>
<div mytable api="data">
<div col="ID"></div>
<div col="NAME"></div>
</div>
CSS
table {
width: 100%;
}
td {
border: 1px solid red;
text-align: center;
padding: 10px;
}
thead td {
background: gray;
color: white;
}
JavaScript
var myApp = angular.module('myApp',[]);
myApp.run(function($rootScope) {
$rootScope.data = [{
id: 1,
name: 'One'
}, {
id: 2,
name: 'Two'
}];
});
myApp.directive('mytable', function() {
return {
restrict: 'AE',
transclude: true,
template:
'<table>\
<thead></thead>\
<tbody>\
<tr ng-repeat="d in data">\
<td ng-bind="d.id"></td>\
<td ng-bind="d.name"></td>\
</tr>\
</tbody>\
</table>',
controller: function($scope, $element, $attrs) {
$scope.data = $scope.$eval($attrs.api);
},
link: function(scope, element, attrs, NullController, $transcludeFn) {
$transcludeFn(function(tElement) {
var headHTML = '<tr>';
for (var i = 0; i < tElement.length; i++) {
if (tElement[i].nodeType === 1) {
headHTML+= '<td>' + angular.element(tElement[i]).attr('col') + '</td>';
}
}
headHTML+= '</tr>';
element.find('thead').html(headHTML);
});
}
};
});