首先,介绍一下背景。基本上,我使用 ng-repeat 在表格中呈现对象列表。我的过滤器需要能够获取搜索字符串,并检查重复对象中的每个搜索词。每个搜索词都需要出现在任何对象属性中(以任何顺序),过滤器才能通过该对象。例如,如果一个对象看起来像这样:
{
customer: 'John Smith',
detail: 'Some details'
}
我的搜索文本是 smith john
或 details john smith
或 smith john details
,它需要能够接受这些术语,以任何顺序,并找到匹配的对象。上面的对象应该匹配,因为所有搜索词都存在。
我写的过滤器如下:
angular.module('app').filter('assetsearch', function () {
return function (input, searchString) {
var searchTerms = searchString === '' ? [] : searchString.replace(/ +/g, ' ').replace(/[^\w\s]|_/g, '').toLowerCase().split(' ');
var matches = _.filter(input, function (asset) {
var textToSearch = [
asset.customer,
asset.details
];
textToSearch = textToSearch.join(' ').replace(/ +/g, ' ').replace(/[^\w\s]|_/g, "").toLowerCase();
var match = true;
_.each(searchTerms, function (term) {
match = (textToSearch.trim().indexOf(term) > -1) && match;
});
return match;
});
return matches;
}
});
我的模板代码看起来很标准,其中 $ctrl
指的是模板的组件 Controller :
<tr ng-repeat="asset in $ctrl.assets | assetsearch:$ctrl.filters.search" ng-if="!asset.loading">
结果
当我搜索“John Smith”、“John”或“Smith”时,它有效 - 当我反转字符串时它只是拒绝工作...当字符串反转为“Smith John”或更改为“Joh Smith',过滤器似乎根本没有被触发(在这种情况下,过滤器功能开始时的控制台日志没有运行,所以它似乎什么也没做)。
最佳答案
我会避免使用下划线和像 replace()
这样的方法来使用 angularjs 通过嵌套的 forEach 循环做一些更简单的事情。过滤器将被重写如下:
app.filter('assetsearch', function() {
return function(input, term) {
var obj = {};
if (typeof term !== 'undefined') {
angular.forEach(input, function(v, i){
var terms = term.split(" ");
angular.forEach(terms, function(v2, i2){
if( v.toLowerCase().indexOf(v2.toLowerCase()) !== -1){
obj[i] = v;
}
});
});
} else {
return input;
}
return obj;
};
});
我还创建了一个 Plunker展示它在真实环境中的工作原理。
关于javascript - Angular JS 自定义过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42528268/