应用jqgrid搜索过滤器工具栏

时间:2016-01-05 10:10:59

标签: javascript jquery html angularjs jqgrid

我是jqGrid的初学者,我有两个问题。

首先,我想在网格中实现搜索工具栏,如下图所示。

我做了分析,发现通过使用下面的代码行将启用搜索工具栏。但我尝试放置它,没有期望的输出。

 jQuery("#overviewJqGrid").jqGrid('navGrid', '#jqGridPager',
{ edit: false, add: false, del: false, search: true }, {}, {}, {}, { closeAfterSearch: true });

enter image description here

JS代码:

app.controller('DiscoveryOverviewCtrl', function ($scope, $rootScope, $compile, localStorageService) {
var gwdth = $("#divGrid").width();


    //TODO: Find a better solution
var WebApiServerUrl = $rootScope.WebApiURL;



$('#DiscoveryReportModel').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget);

    var reportId = button.data('id');
    var machineName = button.data('machinename');

    // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
    // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
    var modal = $(this);

    modal.find('#titleSpan').text('Machine Name / IP Address: ' + machineName)
    $("#tblDiscoveryReport").jqGrid('setGridParam', { url: $rootScope.WebApiURL + "/discovery/" + reportId, datatype: "json" }).trigger("reloadGrid");

    $("#tblDiscoveryReport").jqGrid({

        url: $rootScope.WebApiURL + "/discovery/" + reportId,

        datatype: "json",
        contentType: 'application/json',
        ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
        serializeGridData: function (postData) { return JSON.stringify(postData); },
        colNames: ['Attribute Name', 'Message', 'Attribute Value'],
        colModel: [
            { name: 'attributeName', width: 130 },
            { name: 'message', width: 80 },
            { name: 'attributeValue', formatter: ReportItemStatusImage, width: 40, align: 'center' }
        ],
        loadonce: true,
        width: 550,
        height: 200,
        rowNum: 20,
        rowList: [20, 30, 50],
        sortname: 'Attribute Name',
        viewrecords: true,
        gridview: true,
        sortable: true,
        mtype: 'GET',
        loadBeforeSend: function (xhr) {
            var authData = localStorageService.get('authorizationData');

            if (authData) {
                xhr.setRequestHeader("Authorization", 'Bearer ' + authData.token);
            }
            return xhr;} });

    function ReportItemStatusImage(cellvalue, options, rowObject) {
        if (cellvalue == true) {
            return "<img src='/assets/img/OK.png' height='16' width='16' />";
        }
        else {
            return "<img src='/assets/img/NOK.png' height='16' width='16' />";
        }
    }
});



$scope.config = {

    url: $rootScope.WebApiURL + '/discovery',

    datatype: "json",
    contentType: 'application/json',
    ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
    serializeGridData: function (postData) { return JSON.stringify(postData); },
    width: gwdth,
    height: 550,
    colNames: ['ID', 'Discovery Title', 'Requested Date', 'Completed Date', 'Owner', 'Discovery Status', 'Discoverd Machines'],
    colModel: [
        { name: 'id', key: true, width: 50, sorttype: 'int' },
        { name: 'discoveryTitle', width: 80 },
        { name: 'createdDateTime', width: 80, formatter: 'date', formatoptions: { srcformat: "ISO8601Long", newformat: "m/d/Y h:i:s A" } },
        { name: 'discoveryEndDate', width: 80, formatter: 'date', formatoptions: { srcformat: "ISO8601Long", newformat: "m/d/Y h:i:s A" } },
        { name: 'createdByUser', width: 80 },
        { name: 'discoveryRequestStatus', width: 80 },
        { name: 'discoverdMachinesCount', width: 80, sorttype: 'int' }
    ],

    loadonce: true,
    rowNum: 10,
    rowList: [20, 30, 50],
    sortname: 'id',
    sortorder: "asc",
    viewrecords: true,
    gridview: true,
    mtype: 'GET',
    subGrid: true,
    sortable: true,
    pager: true,
    viewrecords: true,
    gridview: true,
    mtype: 'GET',
    subGridRowExpanded: function (subgrid_id, row_id) {
        // we pass two parameters
        // subgrid_id is a id of the div tag created within a table
        // the row_id is the id of the row
        // If we want to pass additional parameters to the url we can use
        // the method getRowData(row_id) - which returns associative array in type name-value
        // here we can easy construct the following
        var subgrid_table_id;
        subgrid_table_id = subgrid_id + "_t";


        pager_id = "p_" + subgrid_table_id;
        $("#" + subgrid_id).html("<table id='" + subgrid_table_id + "' class='scroll'></table><div id='" + pager_id + "'></div>");

        $("#" + subgrid_table_id).jqGrid({
            url: $rootScope.WebApiURL + '/discovery/' + row_id,
            datatype: "json",
            colNames: ["Id", 'Machine Name / IP Address', 'Status', 'Report'],
            colModel: [
               { name: 'id', key: true, width: 50, sorttype: 'int' },
               { name: 'machineName', width: 200 },
               { name: 'isDiscovered', width: 80, edittype: 'image', formatter: isDiscoveredFormatter, align: "center", search: false },
               { name: 'id', label: 'report', formatter: reportFormatter, width: 75, fixed: true, align: 'center', search: false }
            ],
            height: '100%',
            loadonce:true,
            rowNum: 10,
            rowList: [20, 30, 50],
            sortable: true,
            sortname: 'num',
            sortorder: "asc",
            pager: pager_id,
            loadBeforeSend: function (xhr) {
                var authData = localStorageService.get('authorizationData');

                if (authData) {
                    xhr.setRequestHeader("Authorization", 'Bearer ' + authData.token);
                }
                return xhr;
            }
        });

        jQuery("#" + subgrid_table_id).jqGrid('navGrid', "#" + pager_id, { edit: false, add: false, del: false })
    },
    subGridOptions: {
        // configure the icons from theme rolloer
        plusicon: "ui-icon-triangle-1-e",
        minusicon: "ui-icon-triangle-1-s",
        openicon: "ui-icon-arrowreturn-1-e" }, 
    loadBeforeSend: function (xhr) {
        var authData = localStorageService.get('authorizationData');

        if (authData) {
            xhr.setRequestHeader("Authorization", 'Bearer ' + authData.token);
        }
        return xhr;
    }};
var reportFormatter = function (id, cellp, rowData) {
    var stateLink = "<button type=\"button\" class=\"btn btn-link\" data-toggle=\"modal\" data-target=\"#DiscoveryReportModel\" data-id=\"" + id + "\" data-machinename=\"" + rowData.machineName + "\">Report</button>";
    return stateLink;
};
var isDiscoveredFormatter = function (cellvalue, options, rowObject) {
    if (cellvalue == true)
        return '<img src="\\assets\\img\\OK.png" height="16" width="16" />';
    else
        return '<img src="\\assets\\img\\NOK.png" height="16" width="16" />';
};

//Placed here

 });

HTML代码:

<div class="modal fade" id="DiscoveryReportModel" tabindex="-1" role="dialog" aria-labelledby="DiscoveryReportModelLabel">
<div class="modal-dialog" role="document">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title">Discovery Report</h4>
        </div>
        <div class="modal-body">
            <div class="well with-header with-footer">
                <div class="header bordered-success">
                    <span id="titleSpan">Some title</span>
                </div>

                <div id="divReportGrid">
                    <table id="tblDiscoveryReport"></table>
                </div>                   
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
    </div>
</div>

<div class="row" ng-controller="DiscoveryOverviewCtrl"> <div class="col-xs-12 col-md-12"> <div class="widget"> <div class="widget-header bordered-bottom bordered-themeprimary"> <i class="widget-icon fa fa-tasks themeprimary"></i> <span class="widget-caption">Discovery Overview</span> </div> <div id="divGrid" class="widget-body"> <ng-jq-grid id="overviewJqGrid" config="config" api="api"></ng-jq-grid> <div id="jqGridPager"></div>
</div> </div> </div>

第二个问题是,其他页面上的搜索工具栏不适用于日期字段列。它适用于包含&#39;并且&#39;不包含&#39;在哪里等于&#39;和其他搜索操作导致空白输出。

我尝试使用this&amp;中描述的srcformats。通过this文件提到。

JS代码

$("#jQGridMonitoredMachines").jqGrid({
    url: $rootScope.WebApiURL + '/getallmonitoredmachinerequests',
    datatype: "json",
    contentType: 'application/json',
    ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
    colNames: ['Id', 'Machine Name', 'IP Address', 'Discovered Date', 'Agent Install Status', 'Agent Installation Date', 'Agent Status', 'Agent Version', 'Last HeartBeat Received'],
    colModel: [            
        { name: 'id', hidden: false, width: 20, key: true, sorttype: 'int', search: true },
        { name: 'machineName', width: 120, search: true },
        { name: 'ipAddress', width: 60, search: true },
        //{ name: 'discoveredDate', width: 110, formatter: 'date', formatoptions: { srcformat: 'y-m-d', newformat: 'l, F d, Y' } },    
        //, searchoptions: { sopt: ['eq','ne'], dataInit : function (elem) { $(elem).datepicker({ changeYear: true, changeMonth: true, showButtonPanel: true})} } },
        { name: 'discoveredDate', width: 110, search: true, formatter: 'date', formatoptions: { srcformat: "ISO8601Long", newformat: "m/d/Y h:i:s A" } },
        { name: 'agentInstallStatus', width: 100, search: true },
        { name: 'agentInstallationDate', width: 110, search:true, formatter: 'date', formatoptions: { srcformat: "ISO8601Long", newformat: "m/d/Y h:i:s A" } },
        { name: 'agentStatusName', width: 60, search: true },
        { name: 'agentVersion', width: 50, search: true },
        { name: 'lastHeartBeatRecieved', width: 110, search:true,formatter: 'date', formatoptions: { srcformat: "ISO8601Long", newformat: "m/d/Y h:i:s A" } }
    ],
    rowattr: function (rd) {
        if (rd.agentInstallStatus != 'Completed' && rd.agentInstallStatus != 'Upgrade Completed' && rd.agentInstallStatus != 'Uninstallation Failed') {
            return {
                "class": "ui-state-disabled ui-jqgrid-disablePointerEvents"
            };
        }
    },

    sortname: 'id',
    sortorder: 'asc',
    loadonce: true,
    viewrecords: true,
    gridview: true,      
    width: gwdth,
    height: 650,
    sortable:true,
    rowNum: 30,        
    rowList: [10, 20, 30],
    mtype: 'GET',
    multiselect: true,
    multipleSearch: true,
    pager: "#jqGridPager",

enter image description here

为了使相应的功能有效,我还需要做些什么?

1 个答案:

答案 0 :(得分:0)

  1. 何时执行代码$("#overviewJqGrid").jqGrid('navGrid', '#jqGridPager', ...);?你应该验证它是否会在创建网格后执行来解决你的第一个问题。
  2. 严格建议对子网格数据使用idPrefix以防止ID重复(例如idPrefix: "s_" + row_id + "_")。
  3. 可能更有效地将子网格数据与主数据一起加载
  4. 如果$('#DiscoveryReportModel').on('show.bs.modal', ...可以被多次调用,那么您应该包含GridUnload而不是setGridParam的来电。重要的是要了解$("#overviewJqGrid").jqGrid({...})会将 <table id="overviewJqGrid"></table>转换为相对复杂的div和表结构。因此,有两个主要选项可以在下次调用时刷新数据:setGridParam更改某些选项并触发"reloadGrid"或使用GridUnload销毁先前创建的网格并在其中创建新网格之后使用$("#overviewJqGrid").jqGrid({...})。在setGridParam之前使用$("#overviewJqGrid").jqGrid({...})无法一起使用。
  5. 使用“相等”操作搜索日期的最后一个问题在我看来是完全独立的问题。您使用完整日期时间作为输入数据,并以“m / d / Y h:i:s A”格式显示。用户输入完整日期与时间非常不舒服。输入数据中存在毫秒可能会产生额外的问题。解决方案可能很大程度上取决于您的确切要求和您使用的jqGrid的分支。我大约一年开发免费的jqGrid fork。我实现了自定义排序操作​​,它允许您准确定义比较数据的方式。例如,您可以使用Date only "equal"比较日期,只比较 date 部分而忽略时间部分。我为The old demo创建的the old issue演示了该功能。可以在演示中键入(或选择)“04/15/2015”,过滤后的数据将是“4/15/2015 9:15:40 PM”,“2015/4/15 3:31:下午49点“和”2015年4月15日12:00:00“:

    enter image description here

    最后,我想再添加一个对the old answer的引用,该引用演示了jqGrid对directive的动物的使用。可能这个例子对你也有帮助。