ng-grid totalServerItems问题

时间:2014-06-24 10:51:26

标签: ng-grid

我正在使用ng-grid来显示我返回的JSON数据

restApp.js

function request(method, url, data, params){
    var deferred = $q.defer();

    var fullpath = _server+url;

    if(typeof(data) == 'string'){
        params = data;
        data = null;

        fullpath = fullpath+params;
    }
    //alert(fullpath);

    $http({
        method: method,
        url: fullpath,
        data: data
    }).success(function(data){
    console.log(data);
        deferred.resolve(data);
    }).error(function(err){
        deferred.reject(err);
    });

    return deferred.promise;
}


var getAlertsWithOptions = function(pageNum, per_page, search, sort, public_alert){
    /*Returns all alerts, with the option of specifying 
    pagination, searching and sorting. In case pagination 
    is requested, both parameters ‘page’ and ‘per_page’ can 
    be supplied to customize the pagination. Default value 
    for ‘per_page’ if not supplied will be 10, default for 
    ‘page’ is 1. Sorting is also possible by supplying a 
    ‘sort’ request parameter with any combination of the 
    values ‘priority’, ‘state’, ‘createdAt’, ‘summary’, 
    ‘active’,’details’. Using ‘-‘ in front of the sort 
    field will sort in descending order. Default sort field 
    if no sorting supplied will be ‘-createdAt’. Filtering 
    is provided via the ‘q’ request parameter. This will 
    filter alerts by their ‘summary’ or ‘details’ fields.
    Filtering is case-insensitive*/
    var url = 'alert';
    var params = '';
    //alert(totalServerItems);
    var options = [];
    //alert(pageNum+"--"+per_page+"--"+search+"--"+sort+"--"+public_alert);
        if(typeof(pageNum) != 'undefined'){                
            options.push('page=' + pageNum);
        }
        if(typeof(per_page) != 'undefined'){                
            options.push('per_page=' + per_page);
        }
        if(typeof(search) != 'undefined' || search != null){                
            options.push('q=' + search);
        }
        if(typeof (sort) != 'undefined'){              
            options.push('sort=' + sort);
        }
        if(typeof (public_alert) != 'undefined'){              
            options.push('public=' + public_alert);
        }

        if (options.length > 0) {
            params = '?';
            params = params + options.join('&');                
        }

    return request('GET',url,params);
}

adminAlertCtrl.js

var adminAlertCtrl = angular.module('siApp').controller('adminAlertController',['$scope','restApp', '$modal', 'selectedAlert', 'loadAlerts',
function($scope, restApp, $modal, selectedAlert, loadAlerts){

$scope.displayAlert = false;
$scope.close = function(){$scope.displayAlert = false}
var _currentSort = '';

$scope.sortOptions = [
    {name:"Date", value:"-createdAt"},
    {name:"Priority", value:"priority"},
    {name:"Status", value:"state"},
    {name:"Name",value:"summary"},
    {name:"Details",value:"details"},
    {name:"Privacy", value:"publicAlert"}];

var initLoad = true;
$scope.$watch('sortModel', function(newVal){
    _currentSort = newVal;
    if(initLoad) {
        initLoad = false;
        return;
    }

    //the 1 represents the page starting on. Every time a new sort is specified, we take the user back to the first page of this newly sorted data
    restApp.getAlertsWithOptions(1, $scope.pagingOptions.pageSize, $scope.searchFilter, [_currentSort.value]).then(function(data){
        if (data !== 'No alerts found') {
            //add dateObj to filter
            data.map(function(_alert){
                return _alert.dateObj = new Date(_alert.createdAt).toDateString();
            });
            $scope.myData = data;
        } else {
            $scope.myData = [];
        }
    },function(err){
        alert('Error refreshing alerts: '+ err);
    });
 });


//add dateObj to filter
if(loadAlerts != "No alerts found") {
    loadAlerts.map(function(_alert){
        return _alert.dateObj = new Date(_alert.createdAt).toDateString();
    });
    $scope.myData = loadAlerts;
 }else{
    $scope.displayAlert = true;
    $scope.pageAlert= {type: "warning", message:"No Alerts Found"}
    $scope.myData = [];
 }
$scope.totalServerItems = 0;
 //ngGrid
 $scope.pagingOptions = {
    pageSizes: [5,10,20],
    pageSize: 10,
    currentPage: 1,
    input:'text',
    totalServerItems: 'totalServerItems'
 };

 $scope.gridOptions = {
    columnDefs: [
        {field:"summary", displayName:"Name", sortable:false, cellTemplate: "<div><a ng-click='editAlert(row.entity)'>{{row.entity[col.field]}}</a></div>" },
        {field:"dateObj", displayName:"Date", sortable:false, cellTemplate: "<div>{{row.entity[col.field]}} </div>    "},
        {field:"priority",width:"90px" ,sortable:false, displayName:"Priority", cellTemplate:"<div ng-class='{high: row.getProperty(col.field) === \"HIGH\", med: row.getProperty(col.field) === \"MEDIUM\",  low: row.getProperty(col.field) === \"LOW\" }'>{{row.entity[col.field]}}</div>"},
        {field:"details", displayName: "Details", sortable:false},
        {field:"state", displayName:"Status", sortable:false}
     ],
    enablePaging: true,
    showFooter: true,
    pagingOptions: $scope.pagingOptions,
    multiSelect: false,

    data: 'myData'
 };

    function getPagedDataSet(pageSize, pageNum){
        console.log('page data set');
        console.log(pageSize);
        console.log(pageNum);


        restApp.getAlertsWithOptions(pageNum, pageSize, $scope.searchFilter, [_currentSort.value]).then(function(data){
            console.log('retireved data back for new page');

            //update the new page on the grid
            data.map(function(_alert){
                return _alert.dateObj = new Date(_alert.createdAt).toDateString();
            });
            $scope.totalServerItems = data.length;
            $scope.myData = data;
            alert($scope.totalServerItems);
        },function(err){
            console.log(err);
        })

    }

    $scope.$watch('pagingOptions', function (newVal, oldVal) {

      if (newVal !== oldVal && newVal.currentPage !== oldVal.currentPage) {
            getPagedDataSet($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage);
      }
    }, true);


  function reload(){
   restApp.getAlertsWithOptions(1, $scope.pagingOptions.pageSize, $scope.searchFilter, [_currentSort.value]).then(function(data){
       if (data !== 'No alerts found') {
           //add dateObj to filter
           data.map(function(_alert){
               return _alert.dateObj = new Date(_alert.createdAt).toDateString();
           });
           $scope.myData = data;
       } else {
           $scope.myData = [];
       }
   },function(err){
       alert('Error refreshing alerts: '+ err);
   });
 }

 $scope.searchFilter = '';
 $scope.filter = function(){
   restApp.getAlertsWithOptions(1, $scope.pagingOptions.pageSize,     $scope.searchFilter, ['-createdAt']).then(function(data){
     //add dateObj to filter          
       if (data !== 'No alerts found') {
           data.map(function(_alert){
               return _alert.dateObj = new Date(_alert.createdAt).toDateString();
           });
           $scope.myData = data;
       } else {
           $scope.myData = [];
       }

   },function(err){
       alert('Error searching alerts: '+ err);
   });
 }

 $scope.refresh = function(){
   $scope.displayAlert = false;
   reload();
 }

 $scope.editAlert = function(selAlert){
  //pass alert to selectedAlert

   selAlert = selAlert || {
        "publicAlert" : "1",
        "source" : "S",
        "priority" : "MEDIUM",
        "state" : "NEW"
   };

   selectedAlert.setAlert(selAlert);


   var modalInstance = $modal.open({
       templateUrl: 'views/alertModal.html',
       controller: "alertModalCtrl",
       backdrop: 'static',
       resolve:{
           states: alertCtrl.aStates,
           priorities: alertCtrl.aPriorities
       }
   });

   modalInstance.result.then(function(result){

       var msg = 'Alert Successfully ';
       if (result === 'create') {
           msg += 'Created';
       } else {
           msg += 'Updated';
       }
       reload();
       $scope.pageAlert = {
           "type": 'success',
           "message": msg
       }
       $scope.displayAlert = true;
   },function(){
       console.log('modal canceled');
   })

}
}]);

adminAlertCtrl.loadData = function($q, restApp){
var deferred = $q.defer();

restApp.getAlertsWithOptions(1, 10, undefined, ['-createdAt']).then(function(data){
    deferred.resolve(data);
},function(err){
    deferred.reject(err);
});

return deferred.promise;
}

adminAlertCtrl.aStates = function($q, restApp){
  var deferred = $q.defer();

restApp.getAlertState().then(function(states){
    deferred.resolve(states);
},function(err){
    deferred.reject(err);
});

return deferred.promise;
}

adminAlertCtrl.aPriorities = function($q, restApp){
var deferred = $q.defer();

restApp.getAlertPriority().then(function(priorities){
    deferred.resolve(priorities);
},function(err){
    deferred.reject(err);
});

return deferred.promise;
}

enter image description here

enter image description here

所以,我的问题是我无法获得 totalServerItems 的计数,因此分页无法正常工作。

我的网格共有13个项目,总项目按页数计算,在第一页显示总项目为10,在第二页面中,总otems显示为3。

如果我可以获得总项目计数分页等所有功能都正常工作。 请检查我的代码并帮助我做错的地方。

由于

1 个答案:

答案 0 :(得分:0)

您遇到此问题是因为您仅从服务器接收有关当前页面的数据。 为了使其正常工作,您应该从服务器发送对象,其中包含此搜索和当前页面结果的总行数:

{
    totalServerItems: 13,
    pagedData: Array(10)
}

totalServerItems:移除$scope.pagingOptions属性,因为它属于$scope.gridOptions

$scope.gridOptions = {
    columnDefs: [ ... ],
    enablePaging: true,
    showFooter: true,
    pagingOptions: $scope.pagingOptions,
    multiSelect: false,

    data: 'myData',
    totalServerItems: 'totalServerItems' //like that
};