【问题标题】:AngularJS ui-grid get filtered rows in despite of pagination尽管有分页,AngularJS ui-grid 仍会过滤掉行
【发布时间】:2016-01-30 15:40:19
【问题描述】:

即使我们使用分页,是否有任何解决方案可以从 ui-grid 获取所有过滤的行?我知道有一个方法

$scope.gridApi.core.getVisibleRows($scope.gridApi.grid);

返回页面上所有可见的行。但是当过滤的数据超过一页时,这种方法就没有用了。

【问题讨论】:

    标签: angularjs filtering angular-ui-grid


    【解决方案1】:

    我遇到了和你上面描述的一样的问题。我遇到的任何其他问题是我的网格可以对多个列进行排序,我需要请求某个元素。

    更多细节可以在here找到,一个例子是here

    您可以在下面找到执行此操作的 JS 代码:

    var app = angular.module('stefanz', ['ui.grid', 'ui.grid.pagination']);
    
    app.controller('MyCtrl', ['$scope', 'UIGridCustom', '$http', function($scope, UIGridCustom, $http){
      // A part of data copied from ui-grid demos 
      var data = [{"name": "Ethel Price", "gender": "female", "company": "Enersol" },{"name": "Claudine Neal", "gender": "female", "company": "Sealoud" },{"name": "Beryl Rice", "gender": "female", "company": "Velity" },{"name": "Wilder Gonzales", "gender": "male", "company": "Geekko" },{"name": "Georgina Schultz", "gender": "female", "company": "Suretech" },{"name": "Carroll Buchanan", "gender": "male", "company": "Ecosys" },{"name": "Valarie Atkinson", "gender": "female", "company": "Hopeli" },{"name": "Schroeder Mathews", "gender": "male", "company": "Polarium" },{"name": "Lynda Mendoza", "gender": "female", "company": "Dogspa" },{"name": "Sarah Massey", "gender": "female", "company": "Bisba" },{"name": "Robles Boyle", "gender": "male", "company": "Comtract" },{"name": "Evans Hickman", "gender": "male", "company": "Parleynet" },{"name": "Dawson Barber", "gender": "male", "company": "Dymi" }];
      var colDefs = [{
        label: "name",
        name: "name"
      }, {
        label: "gender",
        name: "gender"
      }, {
        label: "company",
        name: "company"
      }];
    
      // Call the service for init
      var gridOptions = $scope.gridOptions = UIGridCustom.createGridOptions(data, colDefs); 
    
      gridOptions.onRegisterApi = function(api) {
        $scope.gridApi = api;
      }
    
      $scope.getItemPage = function(name) {
        UIGridCustom.jumpToGridItem($scope.gridApi, name); 
      }
    
    }]);
    
    
    app.service('UIGridCustom', ['uiGridConstants', 'utils', function(uiGridConstants, utils){
            var defaultGridOptions = {
                enableColumnMenus: false,
                enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
                enableVerticalScrollbar: uiGridConstants.scrollbars.NEVER,
                enablePaginationControls: false,
                paginationPageSize: 5,
                multipleSorting: true
            };
    
            // Each columns sort rule
            // Position 0 from columnsOrder sorts position 0 from columnDefs and so on
            // Could be overwritten into columnDefs
            // Docs : http://ui-grid.info/docs/#/api/ui.grid.class:GridOptions
            var defaultColSort = [];
    
            //1st column default sorting
            defaultColSort[{
                sort: { direction: uiGridConstants.ASC, priority: 0 }
            }];
    
            // For sorting 2nd column
            // defaultColSort[1] = {
            //     sort: { direction: uiGridConstants.ASC, priority: 0 }
            // };
    
    
            this.createGridOptions = function (gridData, columnDefs, stefanzGridOpts) {
                // Overwrite defaults with custom passed options for grid
                var stefanzGridOpts = typeof stefanzGridOpts !== 'undefined' ? stefanzGridOpts : {};
                var gridOptions = angular.extend({}, defaultGridOptions, stefanzGridOpts);
    
                // Force sorting following the default/custom column sort
                for(var i = 0; i < defaultColSort.length; i++)
                    columnDefs[i] = angular.extend({}, defaultColSort[i], columnDefs[i]);
    
                // Grid init
                gridOptions.data = gridData;
                gridOptions.columnDefs = columnDefs;
                return gridOptions;
            };
    
    
            this.jumpToGridItem = function(api, name) {
                var idx = 0;
                var page = 0;
    
                var sorting = prepareCriteria(api.grid.getColumnSorting());
                var data = dataObjectSort(prepareRows(api.grid.rows), sorting);
    
                entry = getEntryByName(data, name);
                idx = data.indexOf(entry) + 1;
    
                if (!idx)
                    return false;
    
    
                // Calculate the page where the element exists
                page = Math.ceil(idx/api.grid.options.paginationPageSize);
    
                alert(name + 'is found on page ' + page);
                // Jump to page
                api.pagination.seek(page);
    
            };
    
            // Takes the row's entity and put in a new array as a top-level item
            // Userful for further data handling 
            var prepareRows = function(rows) {
                if (rows.length == 0)
                    return false;
    
                var preparedRows = [];
                rows.forEach(function(row){
                    // Do not need to handle the rows that are not in current filter (hidden)
                    if (row.visible == false)
                        return true;
    
                    preparedRows.push(row.entity);
                });
                return preparedRows;
            };
    
            // We are comparing whole enter and as a parameter we are sending a name
            var getEntryByName = function(data, searchedName) {
              for(var i = 0; i < data.length; i++) {
                if (data[i]['name'] == searchedName)
                  return data[i];
              }
    
              return false;
            }
    
            var dataObjectSort = function(data, criteria) {
                return data.sort(utils.dynamicSortMultiple(criteria));
            };
    
            var prepareCriteria = function(colSorting) {
                var sorting = [];
                var fields = [];
    
                // Take just needed fields
                colSorting.forEach(function(column){
                    sorting.push({
                        field: column.field,
                        direction: column.sort.direction,
                        priority: column.sort.priority
                    })
                });
    
                // Sort criterias by priority - UI grid works like this
                // Reason : http://ui-grid.info/docs/#/api/ui.grid.class:GridOptions.columnDef#properties_sort
                sorting.sort(function(a, b){
                  if (a.priority < b.priority) return -1;
                  else if (a.priority > b.priority) return 1;
                  else return 0;
                });
    
                // Prepare fields for sorting 
                sorting.forEach(function(sort){
                    // Dymanic sort (above) needs "-" sign for descendent direction
                    if (sort.direction != uiGridConstants.ASC)
                        sort.field = '-' + sort.field;
                    fields.push(sort.field);
                });
    
                return fields;
            };
    }]);
    
    // Keep utils methods into a separate service
    // Here all sorting methods will appear
    app.service('utils', function(){
    
        function getJsonValue(obj, path) {
            if (!path || path == '') 
                return obj;
    
            path = path.split('.');
    
            var len = path.length;
            for (var i = 0; i < len - 1; i++) {
                var prop = path[i].split(/\[([^\]]+)]/); // indication[4] => [indication, 4]; indication => [indication]
    
                if (prop.length == 1) {
                    obj = obj[prop[0]];
                } else {
                    obj = obj[prop[0]][prop[1]];
                }
            }
    
            var prop = path[len - 1].split(/\[([^\]]+)]/); // indication[4] => [indication, 4]; indication => [indication]
            if (prop.length == 1) {
                return obj[prop[0]];
            } else {
                if (prop.length == 2) {
                    return obj[prop[0]][prop[1]];
                } else {
                    if(prop.length ==3) {
                        return obj[prop[0]][prop[1]]; // this is a hack!
                    } else {
                        return obj[prop[0]][prop[1]][prop[3]]; // this is a hack!
                    }
                }
            }
        };
    
        //https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value-in-javascript/4760279#4760279
        function dynamicSort(property) {
            var sortOrder = 1;
            if(property[0] === "-") {
                sortOrder = -1;
                property = property.substr(1);
            }
            return function (a,b) {
                var aInsensitive = getJsonValue(a, property).toLowerCase();
                var bInsensitive = getJsonValue(b, property).toLowerCase();
                var result = (aInsensitive < bInsensitive) ? -1 : (aInsensitive > bInsensitive) ? 1 : 0;
                return result * sortOrder;
            }
        };
    
        function dynamicSortMultiple(props) {
            return function (obj1, obj2) {
                var i = 0, result = 0, numberOfProperties = props.length;
                while(result === 0 && i < numberOfProperties) {
                    result = dynamicSort(props[i])(obj1, obj2);
                    i++;
                }
                return result;
            }
        };
    
        return {
            getJsonValue: function(obj, path) {
                return getJsonValue(obj, path);
            },
            dynamicSort: function(property) {
                return dynamicSort(property);
            },
            dynamicSortMultiple: function(props) {
                return dynamicSortMultiple(props);
            }
        }
    
    });
    

    【讨论】:

      【解决方案2】:

      我没有找到任何关于过滤数据的文档,所以我使用的方式是完全手动的。

      让我们抓住我们拥有的活动过滤器:

      function getGridUiFilters(){
           var filters_ = _.filter($scope.gridApi.grid.columns, function(_column){
                return _column.filter.term !== undefined && _column.filter.term !== null;
           });
            return filters_;    
      }
      

      现在我们可以获取所有网格数据并使用您在columnDefs 中定义的过滤器对其进行过滤:

      function getFilteredDatagridIds(){
           var gridFilters = getGridUiFilters();
      
           var gridRows = $scope.gridApi.grid.rows;
      
           var dataRows = _.map(gridRows, function(_row){
                 return _row.entity; // our object stored in row
           });
      
            var filteredDataRows = _.filter(dataRows, function(_row){
               var isMatch = true;
      
               angular.forEach(gridFilters, function (_filter) {
                     // call 'condition' method  defined in 'columnDefs'          
                     isMatch = isMatch &&  
                              _filter.filter.condition(_filter.filter.term, _row[_filter.field] );
      
                    });
      
                          return isMatch;
                      });
      
                      return filteredDataRows;
                  }
      

      在我的情况下,columnDefs 看起来像:

      columnDefs: [
                              {displayName: 'Meeting', field: 'name_obj',
                                  enableSorting: true,
                                  enableColumnMenu: false,
                                  cellTemplate: meetingNameCellTemplate,
                                  headerCellTemplate: meetingNameHeaderCellTemplate,
                                  filter: {
                                      condition: function (searchTerm, cellValue) {
                                          return cellValue.name.toLowerCase().indexOf(searchTerm.toLowerCase()) >= 0;
                                      }
                                  }
                              }, ....
      

      所以我相信这个例子会对你有所帮助

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-10-14
        • 1970-01-01
        • 2015-08-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多