我有一个包含多列的表,目前正在使用文本输入(搜索)字段进行过滤:
HTML (简体):
<div class="search">
<input type="text" placeholder="Search" data-ng-model="vm.filter_on" />
</div>
<tr data-ng-repeat="product in vm.data | filter: vm.filter_on>
<td>{{product.id}}</td>
<td>{{product.name}}</td>
<td>{{product.brand}}</td>
</tr>
假设我有以下三种产品:
{
id: 1,
name: "Waffles",
brand: "Walmart",
},
{
name: "Pizza",
brand: "Walmart",
},
{
name: "Soda",
brand: "Target",
}
如果在搜索栏中输入“沃尔玛”,我将看到前两个对象。我想知道的是,是否有可能搜索“沃尔玛皮兹”而仅显示第二个对象-本质上,让搜索词尝试跨多个列的值进行匹配。
在寻找解决方案时,我发现的大部分内容都是关于尝试设置搜索将要考虑的特定列,但是我没有找到能解决我的确切用例的任何东西。
我使用此问题的精巧过滤器创建了一种解决方法,它解决了使用多个片段而不是完整术语进行搜索的问题:AngularJS filter for multiple strings
但是即使那样,我仍然需要将列数据合并为单个字符串,搜索才能工作。有什么方法可以在Angular中更优雅地做到这一点?
答案 0 :(得分:1)
您应该创建custom
过滤器:
angular.module('app', []).controller('ctrl', function($scope) {
var vm = this;
vm.filter_on = "Walmart piz";
vm.data = [
{ id: 1, name: "Waffles", brand: "Walmart" },
{ name: "Pizza", brand: "Walmart" },
{ name: "Soda", brand: "Target" }
]
}).filter('custom', function(){
return function(input, search){
if(!search)
return input;
var items = search.split(' ').filter(x => x).map(x => x.toLowerCase());
return input.filter(x => {
for(var item of items){
var flag = false;
for(var prop in x){
if(prop != '$$hashKey' && (x[prop] + '').toLowerCase().indexOf(item) != -1){
flag = true;
break;
}
}
if(!flag)
return false;
}
return true;
})
}
})
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">
</script>
<div class="search" ng-app='app' ng-controller='ctrl as vm'>
<input type="text" placeholder="Search" ng-model="vm.filter_on" />
<br>
<br>
<table>
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>brand</th>
<tr>
</thead>
<tbody>
<tr data-ng-repeat="product in vm.data | custom: vm.filter_on">
<td>{{product.id}}</td>
<td>{{product.name}}</td>
<td>{{product.brand}}</td>
</tr>
</tbody>
</table>
</div>