我是 Angular 新手,我需要您帮助编写一个自定义过滤器,我可以在其中搜索所有数组对象并获取忽略句点 (.) 和逗号 (,) 的匹配结果。例如,如果我输入“ashton”,我应该得到“stash”和“ashton marton”。但我很茫然,需要一些建议。这是我到目前为止所拥有的。
在我的 angularSearch.html 中我有这个。
<!DOCTYPE html>
<html>
<head>
<script src="js/angular.js"></script>x
<title></title>
</head>
<body ng-app="storeSearch">
<div ng-controller="searchController">
<label>Search: </label>
<input type="text" class="search" ng-model="searchString" placeholder="Search"/>
<table>
<tr ng-repeat="p in products | searchFilter: searchString">
<td>{{p.product_code}}</td>
<td>{{p.subname}}</td>
<td>{{p.description}}</td>
</tr>
</table>
</div>
<script src="app/app.js"></script>
</body>
</html>
我的 app.js 如下所示。
var app = angular.module("storeSearch", []);
app.controller("searchController", ["$scope", function($scope){
$scope.products = [
{
product_title: "A-2368",
description:"Asthon Martin",
sub_name:"2000 model ashton martin"
},
{
product_title:"S-2310",
description:"Stash of money",
sub_name:"Rolls Royce"
},
{
product_title:"h-2369",
description:"Honda Civic 2003",
sub_name:"Marton Ashton, Honda Series"
}
];
}]);
app.filter('searchFilter', function(){
return function(arr, searchString){
if(!searchString){
return arr;
}
var result = [];
searchString = searchString.toLowerCase();
angular.forEach(arr, function(products){
if(products.value.toLowerCase().indexOf(searchString) !== -1){
result.push(products);
}
});
return result;
};
});
最佳答案
为了使过滤器正常工作,您需要更改的一件事是:
products.value.toLowerCase().indexOf(searchString)
value
不是数组的属性,因此请尝试将其更改为:
products.description.toLowerCase().indexOf(searchString)
这将比较属性描述
。现在您可以实现细节了。您的版本导致控制台出现错误,因为 products.value
未定义,并且您尝试在未定义时调用 toLowerCase()
。我的建议将解决这个问题。
更新:
如果您想运行所有属性,您可以尝试像这样扩展循环:
angular.forEach(arr, function(products) {
for (var property in products) {
if (products.hasOwnProperty(property)) {
if (products[property].toLowerCase().indexOf(searchString) !== -1) {
result.push(products);
break;
}
}
}
});
更新2
根据您的评论,您想要稍微修改属性的比较,我猜您还想选择您真正想要比较的属性。
app.filter('searchFilter', function() {
return function(arr, searchString) {
var result, property, activePropertyList;
activePropertyList = ['description', 'product_title', 'sub_name'];
result = [];
function isPartofSearchString(propVal, searchString) {
propVal = propVal.replace(/\W+/g, '').toLowerCase();
return propVal.indexOf(searchString) !== -1;
}
if (!searchString) {
return arr;
}
searchString = searchString.toLowerCase();
angular.forEach(arr, function(products) {
for (property in activePropertyList) {
if (isPartofSearchString(products[property], searchString)) {
result.push(products);
break;
}
}
});
return result;
};
});
函数 isPartofSearchString()
替换您的标准(这使事情变得更清晰)。 activePropertyList[]
定义您想要比较的所有属性的名称。由于您有一个 ||
表达式,因此如果一个属性符合您的条件就足够了 -> 因此 break
可以提高效率。
我知道,这里仍有改进的空间:例如您可以将过滤器的一部分移动到 Controller (比较函数和事件属性的定义),但我想将您的代码保留在本示例的过滤器中。
希望有帮助。
关于javascript - Angular 查询搜索所有数组对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34275300/