The filtering feature in AngularJS ng-options is not functioning correctly

Greetings,
I am a newcomer to angular.
In my current demo application, I have created a list of users with a select filter using ng-option.
There seems to be a bug that I have been unable to identify.
The issue:
When I select the Female option, it filters correctly and displays only Female users.
However, when I select the Male option, it shows the full list without filtering out Female users.
Here is a snippet of my code:
HTML page:

<div class="row" style="margin-top: 15px;">
    <div class="col-lg-2 divPad">
        <!--Sidebar content-->
        <b>Sort by gender:</b>
          <select ng-model="query.gender" class="btn btn-default" >
                  <option value="">All users</option>
                  <option ng-repeat="gender in genders" value="{{gender}}">{{gender}}</option>
              </select>
    </div>
</div>
    <div class="row" style="margin-top: 15px;">
        <div class="col-lg-2 divPad">
            <b>Sort by Hobbies:</b>
        <input class="form-control" ng-model="query.hobby" >
        </div>
    </div>
<div class="row" style="margin-top: 15px;">
    <div class="col-lg-12">
        <ul class="phones">
            <li ng-repeat="user in users | filter:query "  class="thumbnail phone-listing">
                <a href="#/users/{{user.name}}" class="thumb">
                    <img style="margin-top: 15px;" ng-src="{{user.imageUrl}}"></a>
                <a href="#/users/{{user.name}}">{{user.name}}</a>
                <p><b>Hobby:</b> {{user.hobby}}</p>
                 <p><b>Gender:</b> {{user.gender}}</p>
            </li>
        </ul>

    </div>
</div>

The controller code:

zenvaControllers.controller('UserListCtrl', ['$scope', 'User', function ($scope, User) {
    $scope.users = User.query();
    $scope.genders = ["Male", "Female"];
}]);

JSON data:

[
    {
        "name": "Lucy",
        "gender": "Female",
        "hobby": "pets",
        "imageUrl": "img/users/avatar1.png"

    },
    {
        "name": "Betty",
        "gender": "Female",
        "hobby": "pets",
         "imageUrl": "img/users/avatar2.png"
    },
    {
        "name": "Ronald",
        "gender": "Male",
        "hobby": "music",
        "imageUrl": "img/users/avatar3.png"
    },
    {
        "name": "Christopher",
        "gender": "Male",
        "hobby": "sports",
        "imageUrl": "img/users/avatar4.png"
    },
    {
        "name": "Ximena",
        "gender": "Female",
        "hobby": "reading",
        "imageUrl": "img/users/avatar5.png"
    },
    {
        "name": "Paul",
        "gender": "Male",
        "hobby": "shopping",
         "imageUrl": "img/users/avatar6.png"
    },
    {
        "name": "Charlie",
        "gender": "Male",
        "hobby": "pets",
       "imageUrl": "img/users/avatar7.png"
    }
]

Appreciate any assistance provided.

Answer №1

To address both scenarios, I would create two custom filters:

hobbyFilter and genderFilter

Check out the live demonstration on Plunker

iApp.filter('hobbyFilter', function() {
   return function( items, query) {
    var filtered = [];


    if(query.hobby === undefined || query.hobby === ''){
      return items;
    }

    angular.forEach(items, function(item) {
      console.log(item.gender, query.gender);
      if(
        query.hobby !== undefined &&
        query.hobby !== '' &&
        item.hobby.indexOf(query.hobby) >= 0)
        {
          filtered.push(item);
        }
    });

    return filtered;
  };
});


 iApp.filter('genderFilter', function() {
   return function( items, query) {

    var filtered = [];


    if(query.gender === undefined || query.gender === ''){
      return items;
    }

    angular.forEach(items, function(item) {

      if(item.gender === query.gender){
        filtered.push(item);
      }
    });

    return filtered;
  };
});

How to Use:

<li ng-repeat="user in users |  genderFilter:query |  hobbyFilter:query">

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Optimizing with react and mobX: What You Need to Know

I am new to React and MobX and have been studying various tutorials on using both together. Currently, I am working on creating a form where users can select a product through autocomplete functionality using react-select. Once a product is selected, the i ...

Utilize Webpack to integrate redux-form as an external library

I currently have a range of imports in my project, such as: import {Field, reduxForm, FormSection, formValueSelector} from 'redux-form'; My goal is to treat the redux-form imports as an external library so that they do not get included in the b ...

Enhancing the visual display of a webpage using AngularJS

Hello there! I'm currently working on enhancing an angular 1.6 app and have encountered a dilemma that needs solving. Let me provide some context: The page in question is a lengthy form consisting of thirty questions. The client-side logic includes nu ...

Populate vue-multiselect with links from the router

Is there a way to populate the vue-multiselect dropdown with <router-link> options? Typically, router links are defined declaratively in the <template>, but vue-multiselect relies on binding an array of options. Any suggestions on how to approa ...

Caution: The `className` property does not align with Material UI css which may cause issues upon reload

https://i.stack.imgur.com/MxAiY.png If you are facing the error/missing CSS, check out this video for a visual representation. While older versions of similar questions exist on Stack Overflow such as React + Material-UI - Warning: Prop className did not ...

Deactivating the class from a button

On my website, I have 3 buttons that represent different product categories. The initial state of the page should load with the "All Products" button having an active class. However, when clicked, this active class should be removed from the "All Products" ...

I possess a solitary div element that requires dynamic replication

I have a single container and an unspecified number of rows of data. I want to display this data on HTML cards that are generated dynamically based on the number of rows. For example, if there are 10 rows of data, I need to create 10 card elements with ea ...

Retrieving the chosen item from an ng-repeat list within a datalist

Currently, I am utilizing array iteration to identify the selected option based on the ID attribute of the result. Is there a more efficient approach for this task? <input type="text" list="products" ng-model="query" /> <datalist id="products"&g ...

Is there a way for me to generate a preview thumbnail for my video?

Looking to add a preview effect to video thumbnails when users hover over them, displaying a series of frames from the video. Are there any jQuery plugins or tutorials available for creating this effect? ...

Ways to extract the first name and email address from a JSON payload

{ "userID": 1, "userHandle": "username", "first_name": "firstname", "last_name": "lname", "middle_initial": null, "email_address": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4e203d250e29232f27 ...

Determine the upcoming Saturday's date by utilizing a stored procedure in Snowflake

Looking for assistance in retrieving the upcoming Saturday date based on a date field in a table using a Snowflake JavaScript stored procedure. Any suggestions would be greatly appreciated. Running the following query in the Snowflake console provides the ...

Error encountered: Required closing JSX tag for <CCol> was missing

Encountered a strange bug in vscode...while developing an app with react.js. Initially, the tags are displaying correctly in the code file. However, upon saving, the code format changes causing errors during runtime. For instance, here is an example of the ...

What is the best method for passing information to my frontend JavaScript files using Express?

When using ejs to render my html pages, I pass in data in the following manner: collection.find({}).toArray( function (err, results) { res.render('index', { results: results, ...

Conceal the div element if the value is either undefined or empty in AngularJS

I am experiencing an issue where I get 2 different values when I use console.log($scope.variable). The values shown are undefined and ''. Based on this value, I need to hide a div. Here's what I have tried: <div ng-hide="$scope.variable ...

Guidelines for passing a value to a method within a method using JavaScript

I am currently exploring how jQuery can be used to select an element, retrieve an attribute, and assign it a new value. While I have successfully managed to select the element and extract the attribute, I am facing difficulty in setting the attribute using ...

Find and conceal the object within the list that includes the term "Ice"

The teacher's assignment is to create a radio button filter that hides items with the word "Ice" in them, such as "Ice Cream" and "Iced Tea." Here is the current code I have been working on: <!DOCTYPE html> <html> <head> <me ...

Ways to minimize renders while toggling a checkbox

I'm currently working on developing a high-performance checkbox tree component. To manage the checked checkboxes, I am utilizing a parent level state that contains an array of selected checkbox IDs => const [selected, setSelected] = useState([]); ...

How can the issue of v-slot missing in Vue2.7 be resolved?

After executing the given code, the results displayed are captured in Google Chrome. Below is a snippet of the code used: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-e ...

Encountering an error message saying "assignment to undeclared variable"

I'm attempting to incorporate a react icon picker from material-ui-icon-picker However, I keep encountering an error stating "assignment to undeclared variable showPickedIcon" edit( { attributes, className, focus, setAttributes, setFocus, setState ...

I am facing difficulties when trying to map the data using react js/axios

After removing the map function from the code, I encountered an error stating that map is not a function. Can someone please assist me with this issue? Here is the updated code: const [text, setText] = useState([]); const axios = require('axios&ap ...