Angular UI-Grid无限滚动/分页不保留以前的数据

时间:2016-03-10 16:05:28

标签: javascript angularjs angular-ui-grid

我遇到的问题是,当我的滚动条到达底部附近时,它会调用结果集中的下一个100条记录,但是,它会用新的100条记录替换之前的100条记录。我是缺少无限滚动的东西。这是我的控制器逻辑

'use strict';

var first = angular.module('TqimApp');
first.controller('NewGridCtrl',  ['$scope', '$http', 'NewGridService', '$timeout', '$modal', '$interval', '$location', 'uiGridConstants', '$filter', '$rootScope',
function($scope, $http, NewGridService, $timeout, $modal, $interval, $location, uiGridConstants, $filter, $rootScope) {
$( "div[id^='nvtooltip']" ).css( "display" , "none");

var id, af;
$scope.headers = [];
$scope.reportQuery = {};
$scope.gridOptions = {};
$scope.pageNumber=0;
$scope.recordNumber=0;
$scope.totalItemsSize=0;
$scope.modeValue = true;
$scope.orderByColumn=null;
$scope.defaultOrderByColumn=null;
var paginationOptions = { pageNumber: 0, pageSize: 25, sort: null };
var params = [];
var whereColumn=[];
$scope.columnName=null;
$scope.columnValue=null;
$scope.gridApi=null;

var words = tokenize( location.href,  '?'); //20160221 moved, changed path to location.href
var words = splitTheSecond( words,  '&'); //20160221 moved

angular.forEach(words, function(word, idx) { //20160221 moved
    var subw = tokenize( word,  '=');
    params[subw[0]]=subw[1];
});

function tokenize( str, token ){
    if( str == null ) return null;
    var words = str.split( token );
    if( words==null || words.length<2 ) {
          console.log( "tokenize error on parsing path " + str );
          return null;
    }
    return words;
};

function splitTheSecond( arrStr, token){
    if( !$.isArray(arrStr) ) return null;
    return tokenize(arrStr[1], token);
};

$scope.grid = {
    'cd': params['cd'],
    'catCd': params['catCd'],
    'id': params['id'],
    'af': params['af'],
    'isPaged': true,
    'recordNumber': 0,
    'pageSize': 100, //20160221 added
    'pd': params['pd'],                              /* production date*/
    'pg': $scope.pageNumber,                         /* page number */
    'ps': paginationOptions.pageSize,                /* page size */
    'oc': $scope.columnName,                         /* order column name */
    'ov': $scope.columnValue,                        /* order column value */
    'order': paginationOptions.sort,                 /* ASCending or DEScending */
    'rv': params['rv'],                               /* result value*/
    's1': params['s1'],                               /* string1*/
    's2': params['s2'],                               /* string2*/
    's3': params['s3'],                               /* string3*/
    's4': params['s4'],                               /* string4*/
    's5': params['s5'],                               /* string5*/
    'month' : params['month']                         /*month*/
};

if( params.filterIds != undefined ) {
    $scope.grid.filterIds = decodeURIComponent( params.filterIds );
}
if( params.qp != undefined ) {
    var qp = decodeURIComponent( params.qp );
    $scope.grid.qp = JSON.parse(qp);
}

$scope.highlightFilteredHeader = function( row, rowRenderIndex, col, colRenderIndex ) {
    if( col.filters[0].term ){
        return 'header-filtered';
    } else {
        return '';
    }
};

$scope.gridOptions = {
     //columnDefs: $scope.headers,
     enablePaginationControls: true,
     enableFiltering: true,
     enableSorting: true,
     useExternalSorting: true,
     visible: true,
     infiniteScrollDown: true,
     infiniteScrollUp: true,
     exporterMenuCsv: true,
     exporterMenuPdf: false,
     enableGridMenu: true,
};

NewGridService.getHeaders($scope.grid.catCd).then(
          function(result)  {
                var returnArray = [];                   
                for( var i = 0; i < result.length; i++ ){
                      returnArray.push({field: result[i].key, displayName: result[i].name, 
                      enableFiltering: true,  headerCellClass: $scope.highlightFilteredHeader, 
                      filter: { term: "", }});
                }                                         
                $scope.defaultOrderByColumn = $scope.grid.catCd == 'CMP_GRD'? 'complaint_result_id' : 'test_result_id';
                $scope.headers = returnArray;
                $scope.gridOptions.columnDefs = $scope.headers;
         },
         function(error){
             console.error(error);
});

var getPage = function(whereColumn) {
    console.log('getPage');

    $scope.reportQuery.whereColumn = whereColumn;
    $scope.reportQuery.fromIndex = $scope.pageNumber;
    $scope.reportQuery.toIndex = paginationOptions.pageSize;
    $scope.reportQuery.orderByColumn = $scope.sortColumnName;
    $scope.grid.recordNumber = $scope.grid.recordNumber + $scope.grid.pageSize;

    getGridData();
    console.log('Grid Size: '+$scope.grid.recordNumber);
};

$scope.getDataDown = function() {
    if($scope.modeValue) {
        $scope.gridApi.infiniteScroll.dataLoaded().then(function() {
            getPage(whereColumn);
        }).then(function() {
            }
        );
    }
};

$scope.gridOptions.onRegisterApi = function(gridApi) {
           console.log('onRegisterApi');
           $scope.gridApi = gridApi;

           $scope.gridApi.core.on.sortChanged($scope, function(grid,  sortColumns) {
                    console.log('sort changed!');
                    console.log(sortColumns);

                    //20160221 added variable resets
                    $scope.grid.totalRecordCount = 0;
                    $scope.grid.recordNumber = 0;

                    //20160221 added block of code to refresh grid after sort
                    var sortClmnList = [];
                    if(sortColumns.length == 0) {
                        sortClmnList.push($scope.defaultOrderByColumn+" ASC");
                    } else {
                        angular.forEach(sortColumns,  function(sCriteria) {
                            sortClmnList.push(sCriteria.name+" "+sCriteria.sort.direction);
                        });
                    }
                    $scope.grid.sortCriteria = sortClmnList;

                    getGridData();
          });

          $scope.gridApi.core.on.filterChanged( $scope,  function() { //20160221 added
                console.log('filter changed!');

                //20160221 added block of code to refresh grid after filter
                var whereColumn = [];
                angular.forEach($scope.gridOptions.columnDefs,  function(obj) {
                    if(obj.visible) {
                        $scope.column.push(obj.name);
                    }
                    if(obj.filter.term!="" && obj.filter.term!=null) {
                        whereColumn.push(obj.name+","+obj.filter.term);
                    }
                });

                $scope.grid.whereColumn = whereColumn;
                $scope.totalItemsSize = $scope.gridOptions.data.length;
                console.log('$scope.grid.whereColumn='+whereColumn);
                getGridData();

        });
        gridApi.infiniteScroll.on.needLoadMoreData($scope, $scope.getDataDown);
};

function formatDates(data) {
    for (var i = 0; i < data.length; i++) {

        if(data[i].production_Date != null) {
            var currentValue = data[i].production_Date;
            var currentDate = new Date(parseInt(currentValue));
            var month = currentDate.getMonth() + 1;
            var day = currentDate.getDate();
            if( day < 10 ) {
                day = '0'+ day;
            }
            var year = currentDate.getFullYear();
            var date = month + "/" + day + "/" + year;
            data[i].production_date = date;
         }
    }        
};

function getGridData() { 
    NewGridService.getGridData($scope.grid).then(
    function(data){console.log(data);
        formatDates(data);
        $scope.gridOptions.data = data;
        $scope.totalItemsSize = $scope.totalItemsSize + $scope.gridOptions.data.length;
        $scope.gridOptions.data = $scope.gridOptions.data.concat($scope.gridOptions.data);
    },
    function(error){
        console.error(error);
    });
 }
 getGridData();

}]);

1 个答案:

答案 0 :(得分:0)

也许这是你的问题。

function getGridData(){ ... $ scope.gridOptions.data = data; //替换数据 ... $ scope.gridOptions.data = $ scope.gridOptions.data.concat($ scope.gridOptions.data); ... }

见注释行: 因此,在将旧数据与新数据连接之前,您的先前数据将被覆盖。

迎接基督徒