我开始工作AngularJS,并DataTables和奇迹是否可以定制响应DataTables期待。当前对DataTables插件的期望是这样的:
AngularJS
DataTables
{ "draw": 1, "recordsTotal": 57, "recordsFiltered": 5, "data": [...] }
在服务器端,API由 django-tastypie
django-tastypie
服务器的响应是:
{ meta: { limit: 20, next: null, offset: 0, previous: null, total_count: 2 }, objects: [...] }
因此,有没有一种方法可以调整Datatables插件以接受/映射此响应,或者我必须找到一种将期望的字段添加到api的方法?
到目前为止,我已经做到了:
var deptTable = angular.element('#deptManagementTable').DataTable({ processing: true, serverSide: true, pagingType: "simple_numbers", ajax: { url: "/client/api/v1/departments/", data: function(d) { d.limit = d.length; d.offset = d.start; d.dept_name__icontains = d.search.value; }, dataSrc: function(json) { for (var i=0, len=json.objects.length ; i<len ; i++) { json.objects[i].DT_RowId = json.objects[i].dept_id; } return json.objects; } }, aLengthMenu: [ [5, 25, 50, 100], [5, 25, 50, 100] ], iDisplayLength: 5, columns: [ { data: "dept_name" }, { data: "dept_created_on", render: function ( data, type, full, meta ) { var dateCreated = new Date(data); dateCreated = dateCreated.toLocaleDateString(); return dateCreated; } } ] });
任何帮助将不胜感激。
提前致谢 :)
您可以将函数传递给DataTables ajax选项,这将使您完全控制如何在将数据传递给DataTables之前获取和映射数据。
ajax
.DataTable({ serverSide: true, ajax: function(data, callback, settings) { // make a regular ajax request using data.start and data.length $.get('/client/api/v1/departments/', { limit: data.length, offset: data.start, dept_name__icontains: data.search.value }, function(res) { // map your server's response to the DataTables format and pass it to // DataTables' callback callback({ recordsTotal: res.meta.total_count, recordsFiltered: res.meta.total_count, data: res.objects }); }); } });
上面的解决方案已经过jQuery DataTables 1.10.4的测试。
由于这个问题是用Angular标记的,因此这是使用angular-datatables的解决方案。
<div ng-controller="testCtrl"> <table datatable dt-options="dtOptions" dt-columns="dtColumns" class="row-border hover"></table> </div> .controller('testCtrl', function($scope, $http, DTOptionsBuilder, DTColumnBuilder) { $scope.dtOptions = DTOptionsBuilder.newOptions() .withOption('serverSide', true) .withOption('ajax', function(data, callback, settings) { // make an ajax request using data.start and data.length $http.get('/client/api/v1/departments/', { limit: data.length, offset: data.start, dept_name__icontains: data.search.value }).success(function(res) { // map your server's response to the DataTables format and pass it to // DataTables' callback callback({ recordsTotal: res.meta.total_count, recordsFiltered: res.meta.total_count, data: res.objects }); }); }) .withDataProp('data'); // IMPORTANT¹ $scope.dtColumns = [ // your column definitions here ]; });
上面的解决方案已经使用角度数据表0.3.0 +数据表1.10.4进行了测试。
¹这里要注意的重要部分是angular-datatables解决方案需要.withDataProp('data')起作用,而纯jQuery DataTables解决方案则没有data: 'data'选择。
.withDataProp('data')
data: 'data'