我正在使用 AngularJS 的 ngGrid 模块来显示一些分页数据。我希望能够跨多个列进行搜索,但是使用 OR 搜索。
假设我有一列包含以下标题:ID、名称、描述。当我搜索时,我想返回 Id OR name OR description 包含搜索词的所有行。
$scope.pagingOptions = {
pageSizes: [20, 50, 100],
pageSize: 20,
totalServerItems: 0,
currentPage: 1
};
$scope.gridOptions =
{
data: 'myData',
columnDefs: [
{ field: 'id', displayName: 'Id' },
{ field: 'name', displayName: 'Name' },
{ field: 'description', displayName: 'Description' },
{ displayName: 'Actions', cellTemplate: '<input type="button" data-ng-click="doSomething(row.entity)" value="Do Something" />'}],
enablePaging: true,
showFooter: true,
showFilter: true,
pagingOptions: $scope.pagingOptions,
filterOptions: {
filterText: "",
useExternalFilter: false
}
};
我尝试使用默认搜索框,并使用绑定(bind)到 $scope.filterText 的外部输入框来定义自定义过滤器,例如:
$scope.filterUpdated = function () {
$scope.gridOptions.filterOptions.filterText = 'id:' + $scope.filterText + ';name:' + $scope.filterText + ';description:' + $scope.filterText;
};
但是,这似乎对所有列进行了 AND。使用 ngGrid 模块可以实现我想要的吗?
提前致谢,
克里斯
最佳答案
是的,可以做一个 OR 过滤器,但是在 ng-grid 源代码中搜索后,我看不到如何使用他们的 filterOptions.filterText
来完成它。 .那只能做AND过滤。
解决方案是使用 filterOptions.useExternalFilter:true
我也没有找到它的例子,但是在玩了一会儿之后,我知道过滤器实际上是通过重新创建 gridOptions.data
来完成的。对象|数组。这是此过滤器的唯一缺点。
Plunker code is here
所以基本上你的代码看起来像这样 index.html :
<body ng-controller="MyCtrl">
<strong>Filter Name:</strong> </string><input type="text" ng-model="filterName"/>
</br>
OR
</br>
<strong>Filter Age:</strong> </string><input type="text" ng-model="filterAge"/>
</br>
<button ng-click="activateFilter()">Run Filter</button>
<br/>
<br/>
<div class="gridStyle" ng-grid="gridOptions"></div>
</body>
在您的 Controller .js :
app.controller('MyCtrl', function($scope) {
$scope.filterOptions = {
filterText: '',
useExternalFilter: true
};
$scope.activateFilter = function() {
var name = $scope.filterName || null;
var age = ($scope.filterAge) ? $scope.filterAge.toString() : null;
if (!name && !age) name='';
$scope.myData = angular.copy($scope.originalDataSet, []);
$scope.myData = $scope.myData.filter( function(item) {
return (item.name.indexOf(name)>-1 || item.age.toString().indexOf(age) > -1);
});
};
$scope.originalDataSet = [{name: "Moroni", age: 50},
{name: "Tiancum", age: 43},
{name: "Jacob", age: 27},
{name: "Nephi", age: 29},
{name: "Enos", age: 34}];
$scope.myData = angular.copy($scope.originalDataSet, []);
$scope.gridOptions = {
data: 'myData',
filterOptions: $scope.filterOptions
};
});
这只是基本过滤(使用正则表达式和/或转换为小写以获得更好的匹配)。另请注意,如果 name 和 age 都为空,我将 name 设置为 '' 然后每个元素都会在过滤器内返回 true (导致整个数据集返回)。
此选项更适合 动态数据集(读取-服务器馈送),但它也可以正常工作,但会复制原始数据集并在其上应用过滤器。
关于javascript - ngGrid 多列过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16846678/