Home > Web Front-end > JS Tutorial > body text

How to Filter for Multiple Values with AngularJS Filters?

Patricia Arquette
Release: 2024-11-03 14:31:30
Original
890 people have browsed it

How to Filter for Multiple Values with AngularJS Filters?

Filtering for Multiple Values with AngularJS Filters

In AngularJS, you can utilize filters to refine data, such as selecting movies based on multiple genres. If you have an object structure with a genres property, you might want to filter for movies that belong to the "Action" or "Comedy" genres.

Custom Filter Approach

Consider creating a custom filter, which is relatively straightforward. Define your filter as follows:

<code class="javascript">angular.module('myFilters', []).
  filter('bygenre', function() {
    return function(movies, genres) {
      var out = [];
      // Implement your filtering logic here, adding matches to the out variable.
      return out;
    }
  });</code>
Copy after login

Template Usage

In your template, you can incorporate your custom filter like this:

<code class="html"><ul>
    <li ng-repeat="movie in movies | bygenre:genrefilters">{{movie.title}}: {{movie.genre}}</li>
</ul></code>
Copy after login

Dynamic Filter Variable

To filter dynamically based on an array of genres in your scope, you can set the variableX variable as follows:

<code class="javascript">$scope.variableX = {genres: ['Action', 'Comedy']};</code>
Copy after login

This enables you to apply the filter dynamically based on the values in the array.

Example

Here's an example fiddle that demonstrates the approach: https://jsfiddle.net/s39pazfg/

The above is the detailed content of How to Filter for Multiple Values with AngularJS Filters?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template