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

如何在AngularJS(v.1)中实现类Excel表格筛选功能?

AngularJS 1 实现类Excel表格筛选功能解决方案

看起来你已经有了一个不错的开头——写了unique过滤器,但可能卡在了筛选条件与表格数据的联动以及确定按钮的触发逻辑上。我来帮你梳理完整的实现思路和代码,解决这个问题!

第一步:修正你的unique过滤器

首先你的过滤器代码里有个小拼写错误(fiel应该是field),先把它补全:

var myApp = angular.module('myApp', []);

myApp.filter('unique', function () {
  return function (arr, field) {
    var o = {}, i, l = arr.length, r = [];
    for (i = 0; i < l; i += 1) {
      // 修正拼写错误:fiel -> field
      var key = arr[i][field];
      if (!o[key]) {
        o[key] = true;
        r.push(key);
      }
    }
    return r;
  };
});

第二步:控制器核心逻辑设计

我们需要在控制器里管理三类数据:

  • 原始的表格数据
  • 用户选中的筛选条件数组
  • 过滤后要展示的数据

同时要写一个触发过滤的函数,绑定到确定按钮上:

myApp.controller('TableFilterCtrl', function ($scope) {
  // 示例原始表格数据(你可以替换成自己的数据)
  $scope.tableData = [
    { id: 1, category: '电子产品', name: '手机' },
    { id: 2, category: '电子产品', name: '电脑' },
    { id: 3, category: '家居用品', name: '沙发' },
    { id: 4, category: '家居用品', name: '桌子' },
    { id: 5, category: '办公文具', name: '笔记本' }
  ];

  // 存储用户选中的筛选条件(比如选中的分类)
  $scope.selectedFilters = [];
  // 存储过滤后要展示的数据
  $scope.filteredData = angular.copy($scope.tableData);

  // 确定按钮触发的过滤函数
  $scope.applyFilter = function () {
    // 如果没有选中任何条件,直接展示全部数据
    if ($scope.selectedFilters.length === 0) {
      $scope.filteredData = angular.copy($scope.tableData);
      return;
    }

    // 根据选中的条件过滤数据
    $scope.filteredData = $scope.tableData.filter(function (item) {
      // 这里以category字段为例,你可以替换成自己要筛选的字段
      return $scope.selectedFilters.includes(item.category);
    });
  };
});

第三步:HTML视图绑定

现在把筛选控件、按钮和表格和控制器的数据绑定起来:

<div ng-app="myApp" ng-controller="TableFilterCtrl">
  <!-- 筛选区域:展示去重后的复选框选项 -->
  <div class="filter-section">
    <h3>筛选分类</h3>
    <label ng-repeat="category in tableData | unique:'category'">
      <input type="checkbox" ng-model="selectedFilters" ng-value="category">
      {{ category }}
    </label>
    <button ng-click="applyFilter()">确定筛选</button>
  </div>

  <!-- 筛选后的表格 -->
  <table border="1">
    <thead>
      <tr>
        <th>ID</th>
        <th>分类</th>
        <th>名称</th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="item in filteredData">
        <td>{{ item.id }}</td>
        <td>{{ item.category }}</td>
        <td>{{ item.name }}</td>
      </tr>
    </tbody>
  </table>
</div>

关键逻辑解释

  1. unique过滤器:用来从原始数据中提取指定字段的唯一值,作为筛选复选框的选项,避免重复。
  2. selectedFilters数组:通过ng-model和ng-value绑定复选框,自动收集用户选中的筛选条件。
  3. applyFilter函数:点击确定按钮时触发,根据选中的条件过滤原始数据,更新filteredData,表格会自动因为ng-repeat的双向绑定展示筛选结果。
  4. 空筛选处理:如果用户没有勾选任何选项,点击确定后会恢复展示全部数据,提升体验。

这样你就能实现类似Excel的勾选筛选、点击确定展示结果的功能了。如果需要筛选多个字段,只需要扩展筛选区域和过滤逻辑即可!

内容的提问来源于stack exchange,提问作者PK-1825

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:32:42