I am attempting to create a custom table element like this:
<datatable items='tableItems' columns='columnsConfig' />
Here 'tableItems' is my array of items and 'columnsConfig' is configuration for column rendering, something like :
$scope.tableItems = [...];
$scope.columnsConfig = [
{
name: 'check',
with: '20px',
renderer: function (rowItem, cellValue) {
return '<input ng-click="clickHandler()" type="checkbox"/>';
}
},
{name: "person.fullName", text: "Name", visible: true, width: '150px'},
{
name: "person.age",
text: "Age",
renderer: function(rowItem, cellValue) {
return cellValue + ' years old';
}
}
];
Inside renderer function I can specify some additional data processing or templating.
In my directive template I have this:
<tbody>
<tr ng-repeat="item in items">
<td ng-repeat="column in columns"
ng-show="column.visible"
ng-bind-html-unsafe="getCellValue(item, $index)">
</td>
</tr>
</tbody>
where inside 'getCellValue' function I invoking my renderer function. Here is directive code:
angular.module('components', [])
.directive('datatable', function () {
return {
restrict: 'E',
templateUrl: '../pages/component/datatable.html',
scope: {
items: "=",
columns: "="
},
controller: function ($scope, $element) {
$scope.getCellValue = function (item, columnIndex) {
var column = $scope.columns[columnIndex];
// return render function result if it has been defined
if (column.renderer) {
return column.renderer(item, getItemValueByColumnName(item, column.name));
}
// return item value by column
return getItemValueByColumnName(item, column.name);
};
}
}
});
All works fine except ng-... directives. I think I have to do some additional processing of 'renderer' function results via $compile or something but yet I can't figure out how to achieve this. So the question is how make ng directives work when I specify them via my renderer function ?
Thanks.
After some investigations I have found next solution:
//after all DOM manipulations we should recompile parts that has been modified
setTimeout(function () {
applyAfterRenderDOMChanges();
}, 0);
var applyAfterRenderDOMChanges = function () {
var cells = $('td', element).children();
$compile(cells)(scope);
scope.$apply();
};
I have some concerns about efficiency of this solition but it works well so far.