如何在 angularJS 中过滤多个值(OR 操作) [英] How to filter multiple values (OR operation) in angularJS
问题描述
我想在 angular 中使用 filter
并且想要过滤多个值,如果它有一个值,那么它应该被显示.
I want to use the filter
in angular and want to filter for multiple values, if it has either one of the values then it should be displayed.
例如我有这样的结构:
一个对象 movie
,它具有 genres
属性,我想过滤 Action
和 Comedy
.
An object movie
which has the property genres
and I want to filter for Action
and Comedy
.
我知道我可以做filter:({genres: 'Action'} || {genres: 'Comedy'})
,但是如果我想动态过滤它该怎么办.例如.filter: variableX
I know I can do filter:({genres: 'Action'} || {genres: 'Comedy'})
, but what to do if I want to filter it dynamically. E.g. filter: variableX
当我有一组必须过滤的流派时,如何在 $scope
中设置 variableX
?
How do I set variableX
in the $scope
, when I have an array of the genres I have to filter?
我可以将它构造为一个字符串,然后执行一个 eval()
但我不想使用 eval()...
I could construct it as a string and then do an eval()
but I don't want to use eval()...
推荐答案
我只想创建一个自定义过滤器.他们没那么难.
I would just create a custom filter. They are not that hard.
angular.module('myFilters', []).
filter('bygenre', function() {
return function(movies,genres) {
var out = [];
// Filter logic here, adding matches to the out var.
return out;
}
});
模板:
<h1>Movies</h1>
<div ng-init="movies = [
{title:'Man on the Moon', genre:'action'},
{title:'Meet the Robinsons', genre:'family'},
{title:'Sphere', genre:'action'}
];" />
<input type="checkbox" ng-model="genrefilters.action" />Action
<br />
<input type="checkbox" ng-model="genrefilters.family" />Family
<br />{{genrefilters.action}}::{{genrefilters.family}}
<ul>
<li ng-repeat="movie in movies | bygenre:genrefilters">{{movie.title}}: {{movie.genre}}</li>
</ul>
编辑这里是链接:Creating Angular Filters
UPDATE:这是一个 fiddle演示我的建议.
UPDATE: Here is a fiddle that has an exact demo of my suggestion.
这篇关于如何在 angularJS 中过滤多个值(OR 操作)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!