Friday, 15 April 2016

AngularJS DataTable Plugin Rending the HTML with Angular Event Tigger such as ng-click

To make the Angular action trigger from the DataTable plugin, you just need add the below code within the loadDataTable Function.

// Define this function first.
function createdRow(row, data, dataIndex) 
{
 // Recompiling so we can bind Angular directive to the DT
 $compile(angular.element(row).contents())(scope);
}

// Then, add the below line with the "DTOptionsBuilder.newOptions()"
.withOption('createdRow', createdRow);

Please find the sample complete function with above added code.
function getUsersDataTable(scope, $state, $stateParams, DTOptionsBuilder, DTColumnBuilder, DTColumnDefBuilder, $compile, $filter)
{
 scope.searchQuery = '';

 scope.dtInstanceCallback = function (dtInstance) {
  var datatableObj = dtInstance.DataTable;
  scope.tableInstance = datatableObj;
 };
 scope.searchTable = function () {
  var query = scope.searchQuery;

  scope.tableInstance.search(query).draw();
 };
   
 scope.dtOptions = DTOptionsBuilder.newOptions()
  .withOption('ajax', {
   dataSrc: 'data',
   url: 'api/v1/admin/users',
   type: 'GET'
  })
  .withOption('processing', true)
  .withOption('serverSide', true)
  //.withOption("sScrollX", "100%")
  .withDOM('rt<"table-tools-group"<"dt-paginate-wrapper"p><"dt-info-wrapper"i><"dt-length-wrapper"l><"clear">><"clear">')
  .withPaginationType('full')
  .withOption('createdRow', createdRow);

 function createdRow(row, data, dataIndex) 
 {
  // Recompiling so we can bind Angular directive to the DT
  $compile(angular.element(row).contents())(scope);
 }

 scope.dtColumns = [
  DTColumnBuilder.newColumn('id').withTitle('').renderWith(actionEditHtml).notSortable(),
  DTColumnBuilder.newColumn('first_name').withTitle('Name')
   .renderWith(function (data, type, full) {
    return full.first_name + ' ' + full.last_name;
   })
 ];
      
 function actionEditHtml(data, type, full, meta)
 {
  return '' +
   'edit';
 }     
  scope.edit = function (id) {
  console.log('edit id', id);
 }
}
Then, call the above function from the Angular Controller
/* Calling the above function from the Angular Controller */
getUsersDataTable($scope, $state, $stateParams, DTOptionsBuilder, DTColumnBuilder, DTColumnDefBuilder, $compile, $filter);

Below is the HTML Code for view file.

 
  

No comments:

Post a Comment

Please post any queries and comments here.