我如何通过" By"?的选择进行搜索或过滤?让我们说我有一个显示标题和年份的电视节目列表。然后我有一个搜索功能,我可以选择是按标题搜索还是按年份搜索" By"下降。
我为此here添加了一个JS小提琴。我可以通过标题过滤它,但这不是我希望它发生的方式,因为我希望它根据用户的选择更加动态:
<input type="text" class="form-control" ng-model="main.searchInput.title">
HTML:
<div ng-app="app" class="container">
<div class="row" ng-controller="SearchFilterOrderController as main">
<div class="col-md-12">
<div class="page-header"><h3>{{main.title}}</h3></div>
<div class="row">
<div class="col-md-6">
<h4>A list of TV shows</h4>
<ul class="list-group">
<li class="list-group-item" ng-repeat="show in main.shows | filter:main.searchInput | orderBy:main.order.key:main.order.reverse"><span class="glyphicon glyphicon-star" ng-if="show.favorite"></span> {{show.title}} <span class="badge">{{show.year}}</span></li>
</ul>
</div>
<div class="col-md-6">
<h4>Search Text</h4>
<div class="input-group">
<span class="input-group-addon">
<span class="glyphicon glyphicon-search"></span>
</span>
<input type="text" class="form-control" ng-model="main.searchInput.title">
</div>
<h4>By</h4>
<div class="input-group">
<select class="form-control pull-right" ng-model="main.filter" ng-options="filter as filter.desc for filter in main.filterBy"></select>
</div>
<h4>Order</h4>
<select class="form-control pull-right" ng-model="main.order" ng-options="order as order.title for order in main.orders"></select>
</div>
</div>
</div>
</div>
</div>
AngularJS:
var app = angular.module('app', []);
app.controller('SearchFilterOrderController', function() {
var vm = this;
vm.title = 'Search, Filter and Order By';
vm.searchInput = '';
vm.shows = [
{
title: 'Game of Thrones',
year: 2011,
favorite: true
},
{
title: 'Walking Dead',
year: 2010,
favorite: false
},
{
title: 'Firefly',
year: 2002,
favorite: true
},
{
title: 'Banshee',
year: 2013,
favorite: true
},
{
title: 'Greys Anatomy',
year: 2005,
favorite: false
}
];
vm.filterBy = [
{
code: 'title',
desc: 'Title'
},
{
code: 'year',
desc: 'Year'
}
];
vm.orders = [
{
id: 1,
title: 'Year Ascending',
key: 'year',
reverse: false
},
{
id: 2,
title: 'Year Descending',
key: 'year',
reverse: true
},
{
id: 3,
title: 'Title Ascending',
key: 'title',
reverse: false
},
{
id: 4,
title: 'Title Descending',
key: 'title',
reverse: true
}
];
vm.order = vm.orders[0];
});
答案 0 :(得分:3)
您可以创建自定义过滤器,例如:
app.filter('customFilter', function() {
return function(arr, by, value) {
return !value ? arr : arr.filter(function(elem) {
return elem[by.code].toString().toLowerCase().indexOf(value.toLowerCase()) >= 0;
})
}
});
使用它而不是另一个:
<li class="list-group-item" ng-repeat="show in main.shows | customFilter:main.filter:main.searchInput | orderBy:main.order.key:main.order.reverse">
我更改了searchInput变量的名称(删除了标题部分)。并将过滤器初始化为默认使用标题。
以下是修改后的小提琴:https://jsfiddle.net/marduke182/4wbj3oue/3/