You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular Js项目中如何获取UI-grid过滤后的可见数据?

如何在AngularJS的UI-Grid中获取过滤后的可见数据

我之前在项目里也碰到过一模一样的需求——要把UI-Grid过滤后的可见数据拿出来做图表或者其他功能,其实UI-Grid本身就提供了现成的API来搞定这个,不用自己去手动处理过滤逻辑,下面是具体的实现步骤:

1. 确保正确注册Grid API

首先,你需要在配置gridOptions的时候,注册Grid API并把它挂载到作用域上,这样后续才能调用相关方法:

angular.module('yourApp').controller('YourGridController', function($scope) {
  // 初始化gridOptions
  $scope.gridOptions = {
    columnDefs: [
      // 你的列定义,比如:
      { name: 'id' },
      { name: 'name' },
      { name: 'age' }
    ],
    data: [], // 你的原始数据集
    // 注册Grid API
    onRegisterApi: function(gridApi) {
      $scope.gridApi = gridApi;
    }
  };

  // 假设这里是你加载数据的逻辑
  loadYourData().then(function(data) {
    $scope.gridOptions.data = data;
  });
});

2. 获取过滤后的可见数据

当你需要获取当前网格中可见的过滤后数据时,可以调用gridApi.core.getVisibleRows()方法。这个方法会返回所有可见行的数组,每个行对象里的entity属性就是你原始的数据模型,提取这些entity就能得到最终的过滤数据集:

// 比如在按钮点击事件中获取数据
$scope.getFilteredData = function() {
  // 确保Grid API已经初始化
  if (!$scope.gridApi) return;

  // 获取所有可见行
  const visibleRows = $scope.gridApi.core.getVisibleRows($scope.gridOptions.grid);
  // 提取每行的原始数据entity
  const filteredData = visibleRows.map(row => row.entity);

  // 现在filteredData就是你要的过滤后数据,可以用来生成图表等
  console.log('过滤后的结果:', filteredData);
  // 这里调用你的图表生成逻辑
  generateChart(filteredData);
};

3. 实时监听过滤变化(可选)

如果需要在用户调整过滤条件(比如输入搜索词、切换过滤规则)时自动更新数据,可以监听Grid的filterChanged事件:

// 在onRegisterApi回调里添加监听
onRegisterApi: function(gridApi) {
  $scope.gridApi = gridApi;

  // 监听过滤变化事件
  gridApi.core.on.filterChanged($scope, function() {
    // 过滤条件变化时自动获取最新的可见数据
    const visibleRows = gridApi.core.getVisibleRows($scope.gridOptions.grid);
    const filteredData = visibleRows.map(row => row.entity);

    // 更新图表或其他功能的数据源
    updateChartData(filteredData);
  });
}

注意事项

  • 确保在调用getVisibleRows之前,Grid已经完成初始化(比如数据已经加载完成,DOM渲染完毕),如果不确定,可以用$timeout延迟调用,或者在gridApi.core.on.gridRendered事件触发后再执行相关逻辑。
  • getVisibleRows返回的行对象包含了Grid的内部信息,一定要取entity属性才能拿到你原始的数据对象,不要直接使用行对象本身。

内容的提问来源于stack exchange,提问作者Aditya Parmar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:11:13