datable常规配置,百度一大堆
function prepareDatatable(selector, options) {
var defaultOptions = {
autoWidth: true,
deferRender: true,
processing: true,
lengthMenu: [10, 25, 50, 100],
colReorder: true,
stateSave:true,//datatable分页刷新后 固定在当前页
retrieve:true,//和destroy一起,用于屏蔽Cannot reinitialise DataTable提示的
destroy:true,
serverSide: false,//true表示服务器端分页,false表示前端分页
pagingType: "full_numbers",
//有兴趣的话,可以好好研究一下dom,这就很清楚datatable的布局,也好自己加按钮等
//dom: '<"dataTables_header"<"dataTables_toolbar" <"dataTables_controls" r>f>>t<"dataTables_footer row"<"col-md-6 m-t" <"pull-left" l><"pull-left" i>><"col-md-6 m-t"p>><"clearfix">',
dom: '<"dataTables_header"<"dataTables_toolbar" <"dataTables_controls" >f>>t<"dataTables_footer row"<"col-md-6 m-t" <"pull-left" l><"pull-left" i>><"col-md-6 m-t"p>><"clearfix">',
createdRow: function (row, data, dataIndex) {
},
initComplete: function () {
}
}; var tableOption = $.extend(true, {}, defaultOptions);
if (options != null) {
$.extend(true, tableOption, options);
}
return angular.element(selector).DataTable(tableOption);
}
(function () {
var cacModule = angular.module('oplus.cac');
//模型控制器
cacModule.controller('CacJobListCtrl', CacJobListCtrl);
CacJobListCtrl.$inject = ['$scope', '$timeout', '$state', 'cacService', '$http', '$compile', '$uibModal', '$localStorage', '$stateParams', '$filter', '$sessionStorage']; function CacJobListCtrl($scope, $timeout, $state, cacService, $http, $compile, $uibModal, $localStorage, $stateParams, $filter, $sessionStorage) {
var vm = this; vm.views = {
template: {},
tableInstance: null,
findJobStatus: findJobStatus
}; var tableOption = {
id: 'cacJobTable',
order: [[2, 'desc']],//做了后端分页,前端排序就没用了
serverSide: true,
aoColumns: [
{mData: 'templateName', title: '模板'},
{
mData: 'auditParams', title: '检查项',
render: function (data, type, row, meta) {
var auditParams = angular.fromJson(row.auditParams);
var html = '';
for (var i = 0; i < auditParams.length; i++) {
var auditParam = auditParams[i];
html += '脚本:<strong>' + auditParam.scripts.length + '</strong>,' +
'规则:<strong>' + auditParam.ruleExpressions.length + '</strong>,' +
'主机:<strong>' + auditParam.hosts.length + '</strong>' +
'<br>'; }
var actionHtml = '<div>' + html + '</div>';
return actionHtml;
}
},
{
mData: 'createdAt', title: '开始时间',
render: function (data, type, row, meta) {
var createdAt = $filter('date')(row.createdAt, 'yyyy-MM-dd HH:mm:ss');//格式化时间
return createdAt;
}
},
{
mData: 'endedAt', title: '结束时间',
render: function (data, type, row, meta) {
var endedAt = $filter('date')(row.endedAt, 'yyyy-MM-dd HH:mm:ss');
return endedAt;
}
},
{mData: 'createdBy', title: '执行人'},
{
mData: 'id', title: '执行状态',
render: function (data, type, row, meta) {
var id = "'" + row.id + "'";
var jobStatus = row.jobStatus;
var actionHtml = "";
if (jobStatus == "running") {
actionHtml = '<button type="button" class="btn btn-info btn-xs" title="查看" ng-click="cacJobListCtrlVm.views.findJobStatus(' + id + ')">' +
'正在执行</button>';
} else if (jobStatus == "completed") {
actionHtml = '<button type="button" class="btn btn-success btn-xs" title="查看" ng-click="cacJobListCtrlVm.views.findJobStatus(' + id + ')">' +
'成功</button>';
} else {
actionHtml = '<button type="button" class="btn btn-danger btn-xs" title="查看" ng-click="cacJobListCtrlVm.views.findJobStatus(' + id + ')">' +
'失败</button>';
}
return actionHtml;
},
createdCell: function (nTd, sData, oData, iRow, iCol) {
$compile(nTd)($scope);
}
},
{
mData: 'id',
title: '操作',
className: 'text-center',
searchable: false,
orderable: false,
render: function (data, type, row, meta) {
var actionHtml =
'<div class="btn-group">' +
'<a type="button" class="btn btn-default btn-sm" ui-sref="app.cac.result({jobId:\'' + row.id + '\'})">查看结果' +
'</a>' +
'</div>';
return actionHtml;
},
createdCell: function (nTd, sData, oData, iRow, iCol) {
$compile(nTd)($scope);
}
}
]
};
//这里包含了几种datatable通过ajax获取数据的几种方式
function init() {
if (_appconfig.modules.cac.useLocalDb) {
//1、
tableOption.ajax = {
url: 'app/modules/cac/api/job.json',
dataSrc: "aaData"
};
} else {
var token = $localStorage.authenticationToken || $sessionStorage.authenticationToken;
//2、使用后台分页就只能使用这种,这种请求ajax会自带start和length参数到后台。不然就自己重新前端的分页方法
tableOption.ajax = {
url: _appconfig.apiBaseUrls.cac + '/api/cac/audit/jobs',
dataSrc: "data",
async: false,
//加headers是为了加token,方便后台的验证
headers: {
"Authorization": 'Bearer ' + token,
"X-JWT-Authorization": 'Bearer ' + token
}
};
//这里还可以用$http();
//3、
$http({
url: _appconfig.apiBaseUrls.cac + '/api/cac/audit/hosts'
}).success(function (ciList, status, header, config, statusText) {
tableOption.ajax = function (data, callback, settings) {
callback(
cacService.assembleTable(ciList)
);
}; $timeout(function () {
cacService.prepareDatatable(".cac-template-host-dialog .cac-template-host-table", tableOption);
}, 10);
}).error(function (data, header, config, status) {
console.log("Finish $http ajax error");
});
//将后台返回的List数据组装成datatable要求的数据格式
function assembleTable(ciList) {
var tableObj = {
aaData: [],
totalRecords: 0
};
tableObj.aaData = ciList;
tableObj.totalRecords = ciList.length;
return tableObj
}
}
$timeout(function () {
//初始化datatables,并保存实例
vm.views.tableInstance = cacService.prepareDatatable(".jobTableDiv .jobTable", tableOption);
}, 10); var template = $stateParams.template;
if (template != null) {
$state.go("app.cac.job.addJob", {template: template});
}
} function findJobStatus(id) {
$uibModal.open({
templateUrl: 'app/modules/cac/job/job-run-log.html',
controller: 'CacJobRunLogCtrl',
controllerAs: 'cacJobRunLogVm',
backdrop: 'static',
size: 'lg',//设置模态框大小
resolve: {
entity: function () {
return {
id: id
}
}
}
}).result.then(function (result) {
});
} init(); } })
();
java后台
@GetMapping("/jobs")
@ResponseBody
public JSONObject getAllTestPages(@RequestParam(value = "start", defaultValue = "0") Integer start,
@RequestParam(value = "length", defaultValue = "10") Integer length) {
Sort sort = new Sort(Sort.Direction.DESC, "createdAt");//后台排序
Pageable pageable = new PageRequest(start / length, length, sort);
Page<AuditJob> page = auditJobRepository.findAll(pageable);
/**后台要返回datatable要求的属性,draw就不需要返回了,因为每次请求的draw是不相同的,每一次前端请求draw都会自增,也会传递到后台,所以后台无需做处理也会自动返回去,做处理就是多此一举而且还很麻烦*/
JSONObject jsonObject = new JSONObject();
//将获取的数据组装成Datatable标准格式返回
jsonObject.put("data", page.getContent());
//数据总条数
jsonObject.put("recordsTotal", page.getTotalElements());
//过滤查询后的条数
jsonObject.put("recordsFiltered", page.getTotalElements());
return jsonObject;
}