angularjs - 在逗号分隔的对象列和另一列上应用过滤器
问题描述
当我尝试在一个对象的多个列上应用过滤器时,我遇到了一个问题。我需要根据选定的下拉列表应用这些过滤器:一个下拉列表直接链接到 id,而另一个值包含名称,但必须根据列表列进行过滤。假设如果选择 def 它应该显示
1 def
2 ghi
我的数据将是
$scope.items =[
{ id: 1, list: ['abc','cde'], name: 'abc'},
{ id: 2, list: ['def','abc'], name: 'def'},
{ id: 3, list: ['def','ghi'], name: 'ghi'},
];
我的html代码是
<tr ng-repeat="item in items| filter:searchText">
{{item.id}} {{item.name}}
</tr>
由于必须在用户单击按钮时应用过滤器,因此将它们写在提交功能下;这是我在控制器中的过滤器代码:
$scope.filtr = {};
//$scope.filtr.id & $scope.filtr.list are the filters hold the value of drop-downs
$scope.submit = function() {
for(prop in $scope.filtr) {
$scope.searchText[prop] = $scope.filtr[prop];
}
}
解决方案
您应该创建custom
过滤器:
angular.module('app', []).controller('ctrl', function($scope) {
$scope.searchText = {};
$scope.items = [
{ id: 1, list: ['abc', 'cde'], name: 'abc' },
{ id: 2, list: ['def', 'abc'], name: 'def' },
{ id: 3, list: ['def', 'ghi'], name: 'ghi' }
];
$scope.visibleItems = $scope.items;
$scope.FilterArray = function(){
function normilize(x){
return (x + '').toLowerCase();
}
$scope.visibleItems = $scope.items.filter(function(x) {
for(var prop in $scope.searchText){
var searchVal = normilize($scope.searchText[prop]);
if(Array.isArray(x[prop])) {
if(!x[prop].some(x => normilize(x).indexOf(searchVal) != -1))
return false;
}
else{
var originVal = normilize(x[prop]);
if(originVal.indexOf(searchVal) === -1)
return false;
}
}
return true;
})
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">
</script>
<div ng-app='app' ng-controller='ctrl'>
list: <input type='text' ng-model='searchText.list'/>
name: <input type='text' ng-model='searchText.name'/>
<button ng-click='FilterArray()'>Apply filters</button>
<ul >
<li ng-repeat="item in visibleItems">
{{item}}
</li>
</ul>
</div>
推荐阅读
- python - RequestsLibrary - 如何在同一个 POST 请求中发送数据和文件
- c# - 使用 CefSharp SendKeyEvent 时,我无法键入文档
- javascript - 如何避免 AudioContext 接口中的“HTMLMediaElement 之前已连接到不同的 MediaElementSourceNode”?
- networking - 奇怪的网络活动 - tcpkill 不工作,端口 4001
- c# - AutoMapper - 映射不同命名空间中的类
- postgresql - Cloud SQL Postgres 中的密码重置问题
- docker - 在 docker 容器中设置了 CPU 限制的巨大 CPU 使用率
- c# - 为什么VS2019的项目属性中没有出现Code Contracts
- autohotkey - AutoHotkey:将特殊字符写入文件
- c# - 如何使用 EF Core Fluent API 设计动态表数据结构?