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

AngularJS过滤需求咨询:搜索‘1’需仅返回完全匹配‘1’的结果

解决AngularJS ng-table特定搜索词完全匹配的需求

默认ng-table的text过滤器是模糊匹配,要实现搜索内容为'1'时仅返回完全匹配结果,其他搜索词保持原有模糊匹配逻辑,你需要自定义过滤函数:

1. 在控制器中添加自定义过滤函数

// 替换成你的实际控制器名称
app.controller('UserTableController', function($scope) {
  // 示例数据,替换为你的业务数据
  $scope.data = [
    { name: '张三', age: '1', location: '北京' },
    { name: '李四', age: '12', location: '上海' },
    { name: '王五', age: '21', location: '广州' }
  ];

  // 自定义过滤逻辑:搜索词为'1'时严格完全匹配,其他情况模糊匹配
  $scope.customMatchFilter = function(item, searchTerm) {
    if (!searchTerm) return true;
    
    // 针对'1'做严格匹配
    if (searchTerm === '1') {
      // 若字段是数字类型,改为 Number(searchTerm) 避免类型不匹配
      return item[this.field] === searchTerm;
    }
    
    // 其他搜索词保持不区分大小写的模糊匹配
    return String(item[this.field]).toLowerCase().includes(searchTerm.toLowerCase());
  };
});

2. 修改HTML中的过滤器配置

把需要应用该逻辑的字段的filter值从'text'替换为自定义函数:

<table ng-table="usersTable" show-filter=true class="table table-bordered table-striped">
  <tr ng-repeat="user in data">
    <td data-title="'Name'" sortable="'name'" filter="{ 'name': 'text' }">{{user.name}}</td>
    <!-- 对age字段应用自定义过滤逻辑 -->
    <td data-title="'Age'" sortable="'age'" filter="{ 'age': customMatchFilter }">{{user.age}}</td>
    <td data-title="'Location'" sortable="'location'" filter="{ 'location': 'text' }">{{user.location}}</td>
  </tr>
</table>

补充说明

  • 如果需要给多个字段应用这个逻辑,只需要把对应字段的filter配置换成customMatchFilter即可。
  • 注意字段的数据类型:如果你的字段是数字类型(比如age存的是数字而非字符串),需要把判断逻辑改成return item[this.field] === Number(searchTerm);,避免类型不匹配导致的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 17:01:10