gpt4 book ai didi

javascript - 从对象列表中过滤($filter)匹配值,排除不必要的属性

转载 作者:行者123 更新时间:2023-12-03 08:57:12 27 4
gpt4 key购买 nike

我正在尝试修改 Smart Table 的行为通过定义我的自定义过滤器 st-set-filter="myCustomFilter" 进行全局搜索。在这里

.filter('myCustomFilter', ['$filter', function($filter){
return function(input, predicate){
return $filter('filter')(input, predicate, false);
}
}])

智能表输入是对象列表,它们的属性是列的名称。 我只想过滤给定的表格列子集

如果我在输入 foo 后在 console.log predicate 中看到类似 Object {$: "foo"} 的内容。这意味着过滤器正在寻找与列表中对象的任何属性(即列)的匹配项。

有没有办法根据我的需求正确定义谓词(例如排除不必要的属性?

最佳答案

只需将该排除逻辑放入您的过滤谓词中即可。您可以通过函数名称将该谓词直接传递给 HTML。

谓词函数是一个接受一些参数(通常是一个对象)并返回 true 或 false 值的函数。该谓词通常会在数组的每个元素上单独计算。以$filter为例,谓词确定是否包含或排除该元素。这意味着您只需编写该函数即可正确包含正确的元素,同时排除错误的元素。

来自documentation for angular's $filter ,谓词具有以下签名:

function(value, index, array): A predicate function can be used to write arbitrary filters. The function is called for each element of the array, with the element, its index, and the entire array itself as arguments.

您不必使用所有输入,通常您只需要第一个参数(元素本身)。您的过滤谓词可能如下所示:

$scope.customFilter = function(item, index, array) {
var excluded = item.testResult == 'fail';
//.contains() logic for a search filter
var included = item.name.toLowerCase().indexOf($scope.filterData.name.toLowerCase()) > -1;

return included && !excluded;
};

然后只需将谓词函数本身传递给 HTML 中的过滤器即可:

<div ng-repeat="obj in data | filter:customFilter">
Do stuff with the filtered data
</div>

我已链接 a demo on plnkr这演示了谓词如何与表单的其他部分交互以包含某些元素同时排除其他元素的基本思想。

<小时/>

关于智能 table 。我不确定您的智能 table 期望什么,但如果只是想要 $filter对象,那么您应该能够利用predicate $filter 的参数。只需使用 filterName:arg1 将谓词函数(如上面所示的函数)传递到自定义过滤器中即可。我从 Todd Motto's page 了解到这个语法(第 3 节:过滤带参数的重复项)。

过滤器定义

//same as your filter, but named a bit better
.filter('appLevelFilter', ['$filter', function($filter){
return function(input, predicate){
return $filter('filter')(input, predicate, false);
}
}])

HTML

<div ng-repeat="obj in data | appLevelFilter:customFilter">
Do stuff with the filtered data
</div>

关于javascript - 从对象列表中过滤($filter)匹配值,排除不必要的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32442331/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com