如何在 angularJS 中过滤多个值(OR 操作) [英] How to filter multiple values (OR operation) in angularJS

查看:18
本文介绍了如何在 angularJS 中过滤多个值(OR 操作)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 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 属性,我想过滤 ActionComedy.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆