简体   繁体   English

DataTables 如何在具有 ajax 数据源的表上添加行号

[英]DataTables How can I add row numbers on a table with ajax data source

I use Angular App and DataTables.我使用 Angular App 和 DataTables。 In one of my components I have a DataTable which pulls data from an external API using the "ajax" property of the options object.在我的一个组件中,我有一个数据表,它使用选项 object 的“ajax”属性从外部 API 中提取数据。

export class ChartsDetailsComponent implements OnInit {
  ngOnInit(): void {
   var opts: any = {
       ajax :{
          url: this.appConfigService.analyseConfig.chartsApiUrl + "/api/Charts/GetChartDetails?type=" + this.chartType,
          dataSrc: "ChartData." + this.chartType
       },
       columns:[
                  {title:"Name"},
                  {title:"Status"},
       ] 
   };
   var table = $('#details').DataTable(opts); 
  }
}

The returned data has the following structure:返回的数据具有以下结构:

{
"ChartData":{
            "FQCInLocalChart":[
                               ["EM/AC.08.2.01","Remote"],
                               ["EM/AC.08.2.03","Remote"]
                              ]
            }
 }

The FQCInLocalChart is dynamic. FQCInLocalChart是动态的。 It is not static property.它不是 static 属性。 That's why in the dataSrc property I put "ChartData." + this.chartType这就是我在dataSrc属性中放置"ChartData." + this.chartType "ChartData." + this.chartType , where this.chartType is a private property of the Angular component. "ChartData." + this.chartType ,其中this.chartType是 Angular 组件的私有属性。

The data source contains only the columns that has to be displayed, but I would like to have a row number before the columns that are filled with the returned from the API data.数据源仅包含必须显示的列,但我希望在填充 API 数据返回的列之前有一个行号。 Is there a way to achieve this behavior?有没有办法实现这种行为?

Thanks in advance Julian在此先感谢朱利安

One approach is to use DataTables events to add and update a column of row numbers to your table.一种方法是使用 DataTables 事件向表中添加和更新一列行号。 There are two aspects to this: (1) the initial rendering of the table;这有两个方面:(1)表格的初始渲染; (2) subsequent re-draws for sorting and filtering. (2) 后续重新抽取进行排序过滤。

For my demo, instead of using ajax, I will provide hard-coded data - but my approach should be compatible with your ajax approach.对于我的演示,我将提供硬编码数据而不是使用 ajax - 但我的方法应该与您的 ajax 方法兼容。

The table:桌子:

 <table id="example" class="display dataTable cell-border" style="width:100%">
 </table>

My test data:我的测试数据:

var dataSet = {
    "ChartData": {
        "FQCInLocalChart": [
            ["EM/AC.08.2.01", "Remote1"],
            ["EM/AD.08.2.01", "Remote2"],
            ["EM/AC.08.2.01", "Remote3"],
            ["EM/AC.08.2.03", "Remote2"]
        ]
    }
};

The dataTable code:数据表代码:

$(document).ready(function() {

    var table = $('#example').DataTable( {
      data: dataSet.ChartData.FQCInLocalChart,
      columns: [
        { title: "Name" },
        { title: "Status" }
      ],
      "initComplete": function() {
        addColNumbers();
      }
    } );

    table.on( 'draw', function () {
      rewriteColNumbers()
    } );

    function addColNumbers() {
      $('#example thead tr').prepend('<th>Num.</th>');
      $('#example tbody tr').each(function( index ) {
        $(this).prepend('<td>' + (index + 1) + '</td>');
      } );
    }

    function rewriteColNumbers() {
      $('#example tbody tr').each(function( index ) {
        $('td', this ).first().html(index + 1);
      } );
    }

} );

In the above approach, the initComplete() function handles the addition of a new column to the table.在上述方法中, initComplete() function 处理向表中添加新列。

And the table.on( 'draw' ) function captures subsequent re-draws for sorting/filtering. table.on( 'draw' ) function 捕获后续重新绘制以进行排序/过滤。

The end result:最终结果:

在此处输入图像描述

This approach means that the data in this new column is not visible to DataTables (it only gets added to the DOM) - and therefore does not take part in any sorting/filtering.这种方法意味着这个新列中的数据对 DataTables 不可见(它只被添加到 DOM)——因此不参与任何排序/过滤。

It also means the data would not be a part of any data export, if you use DataTables export add-ons.这也意味着如果您使用 DataTables 导出插件,数据将不会成为任何数据导出的一部分。

You may want to add some styling/css to this new column, to control its width.您可能想向这个新列添加一些样式/css,以控制其宽度。

I managed to solve my problem.我设法解决了我的问题。 Here is how I've done it: First I've changed the dataSrc property to be function , not string :以下是我的做法:首先,我将dataSrc属性更改为function ,而不是string

export class ChartsDetailsComponent implements OnInit {
  chartType: string = "FQCInLocalChart";

  convertData(json: object){
     var ret = <Array<Array<string>>>json["ChartData"][this.chartType];
     ret.map((value)=>{
           value.unshift('');
         });
   return ret;
  }
  ngOnInit(): void {
    var opts: any = {
      ajax :{
      url: this.appConfigService.analyseConfig.chartsApiUrl + "/api/Charts/GetChartDetails?type=" + this.chartType,
      dataSrc: this.converData.bind(this)
      },
      columns:[
              {title:"Nr."},
              {title:"Name"},
              {title:"Status"},
      ] 
  };
  var table = $('#details').DataTable(opts); 
  table.on('order.dt search.dt', function () {
  table.column(0, { search: 'applied', order: 'applied' }).nodes().each(function (cell, i) {
    cell.innerHTML = i + 1;
    });
  });

 }
}

Basically I hook to the dataSrc function from the angular component and bind the context to be the class of the component, that is how I gained access to the this.chartType property, added another element in front of the element of the array (to hold the row number) and then at the end hook up the table.on() order and search events, to fill up the row numbers itself.基本上我从 angular 组件挂钩到dataSrc function 并将上下文绑定到组件的 class,这就是我如何访问this.chartType属性,在数组元素前面添加另一个元素(以保存行号),然后在最后连接table.on() ordersearch事件,以填充行号本身。

I hope this will help somebody with same or similar problem as mine!我希望这会帮助与我有相同或相似问题的人!

Regards,问候,

Julian朱利安

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM