Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render a column with model binding using angular-datatables?

Is there a way to render a column with model binding in textbox using DTColumnBuilder?

Something like:

DTColumnBuilder.newColumn('ColumnName').withTitle('Column Name').renderWith(function (data) {
   return '<input type="text" ng-model="ColumnName" />';
}),
like image 420
Nikko Reyes Avatar asked Nov 03 '15 02:11

Nikko Reyes


2 Answers

No. You can render the table with (example) :

DTColumnBuilder.newColumn('firstName', 'First name')
  .renderWith(function (data) {
       return '<input type="text" ng-model="json.firstName" />'
}),

but the ng-model is never recognized because it is not angular itself that do the rendering. If you let angular do the rendering, i.e datatable="ng" and ng-repeat it works :

<table datatable="ng" dt-options="dtOptions" dt-columns="dtColumns">
   <tr ng-repeat="item in json">
       <td>{{ item.id }} </td>
       <td><input ng-model="item.firstName"/></td>
       <td>{{ item.lastName }} </td>
   </tr>
</table> 

demo -> http://plnkr.co/edit/f0ycjJvsACaumY13IVUZ?p=preview
notice that the JSON items is updated when you are editing in the input boxes.

like image 93
davidkonrad Avatar answered Nov 08 '22 04:11

davidkonrad


Had the same problem, here is my solution:

  1. Register callback for dtInstance
  2. On "draw.dt" from DataTable $compile related html with angular

In other words:

HTML:

<table datatable=""
       dt-options="vm.dtOptions"
       dt-columns="vm.dtColumns"
       dt-instance="vm.dtInstanceCallback"
       class="table table-bordered table-condensed">
</table>

JS:

renderWith(function(data, type, full) {
    return `<a class="ng-scope"><span ng-click='vm.remove("${data}")' class='fa fa-times-circle'></span></a>`
});
...
vm.dtInstanceCallback = (dtInstance) => {
    vm.dtInstance = dtInstance;
    dtInstance.DataTable.on('draw.dt', () => {
        let elements = angular.element("#" + dtInstance.id + " .ng-scope");
        angular.forEach(elements, (element) => {
            $compile(element)($scope)
        })
    });
}

I minimized selection of elements, to optimize performance, maybe it's not needed. So far tested in Chrome & Safari, worked in both

like image 3
mavarazy Avatar answered Nov 08 '22 03:11

mavarazy