Home > Article > Web Front-end > How to Filter for Multiple Values in AngularJS without Eval()?
Filtering Multiple Values in AngularJS
AngularJS provides a powerful filter feature, but filtering for multiple values using the logical OR operator can be complex. Let's explore how to dynamically filter for multiple values without resorting to potentially dangerous eval() calls.
To achieve dynamic multi-value filtering, we recommend creating a custom filter. Filters are easy to create and provide a secure and efficient way to extend the filtering capabilities of AngularJS.
<code class="javascript">angular.module('myFilters', []). filter('bygenre', function() { return function(movies, genres) { var out = []; for (var i = 0; i < movies.length; i++) { var movie = movies[i]; if (genres.indexOf(movie.genre) !== -1) { out.push(movie); } } return out; } });
This custom filter, named 'bygenre,' takes two parameters: movies (the data to be filtered) and genres (the array of genres to filter for). The filter checks each movie against the specified genres and returns a new array containing only the movies that match any of the genres.
In the template, we can use this custom filter like so:
<code class="html"><h1 ng-init="movies = [ {title:'Man on the Moon', genre:'action'}, {title:'Meet the Robinsons', genre:'family'}, {title:'Sphere', genre:'action'} ];">Movies</h1> <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></code>
This template creates a checkbox for each genre, allowing you to dynamically select which genres to filter for. As you toggle the checkboxes, the movies are filtered to display only those that match the selected genres.
This approach provides a flexible and secure way to filter data dynamically in AngularJS, allowing you to easily search for multiple values without compromising performance or security.
The above is the detailed content of How to Filter for Multiple Values in AngularJS without Eval()?. For more information, please follow other related articles on the PHP Chinese website!