Using Angular JS to filter ng-repeat with a combination of a field and a dropdown

There seems to be a lot of conflicting information online regarding this issue, but I am in search of a concise solution.

My dataset consists of a list of countries around the world, including their name, ISO alpha code, region, and more.

To display this data in a table, I am using an ng-repeat:

<tr ng-repeat="i in filteredItems = (iso3166 | filter: countryFilter)">

Within the table, I have a text field and a dropdown for filtering the list.

The text field is intended to filter by country name or ISO alpha code.

<input type="text" id="countrySearch" placeholder="Country" ng-model="countryQuery">

This functionality is achieved with the following code in the Controller:

    $scope.countryFilter = function (value) {
      if (angular.isUndefined($scope.countryQuery) || $scope.countryQuery === '') {
        return true;
      }
       return value.name.indexOf($scope.countryQuery) >= 0 || value.alpha_2.indexOf($scope.countryQuery) >= 0;
    };

The challenge lies in integrating the dropdown menu. The dropdown contains an array of objects representing different regions of the world, such as:

$scope.regionMenu = [
    {
      label: 'Show All',
      value: ''
    },
    {
      label: 'EU',
      value: 'Europe'
    },...

and

<select ng-model="region" ng-options="s.value as s.label for s in regionMenu"></select>

The objective is for the input field and dropdown to work together, filtering the items based on:

(ISO alpha-2 OR Name) AND (region chosen in menu)

Any guidance on modifying the countryFilter function or rewriting it entirely to achieve this would be greatly appreciated.

Answer №1

Consider these two different approaches:

Option 1: Add an Additional Filter

While this method is simpler, it may not be as efficient as it requires scanning through all array elements twice (unlike option 2).

Controller:

$scope.regionFilter = function (value) {
  if (angular.isUndefined($scope.region) || $scope.region === '') {
    return true;
  }
  return value.region === $scope.region;
};

Template:

<tr ng-repeat="i in filteredItems = (iso3166 | filter: countryFilter | filter: regionFilter)">

Option 2: Combine Filters

$scope.countryFilter = function (value) {
  var passCountry;
  if (angular.isUndefined($scope.countryQuery) || $scope.countryQuery === '') {
    passCountry = true;
  }
  else {
    passCountry = value.name.indexOf($scope.countryQuery) >= 0 || value.alpha_2.indexOf($scope.countryQuery) >= 0;
  }

  var passRegion;
  if (angular.isUndefined($scope.region) || $scope.region === '') {
    passRegion = true;
  }
  else {
    passRegion = value.region === $scope.region;
  }

  return passCountry && passRegion;
};

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

Angular 7+: Trouble with displaying images from assets directory

Details regarding my Angular version: Angular CLI: 7.3.9 Node: 10.15.3 OS: win32 x64 Angular: 7.2.15 ... animations, common, compiler, compiler-cli, core, forms ... language-service, platform-browser, platform-browser-dynamic ... rout ...

Quirks in TailwindCSS template literals behavior

Looking at this specific component: const SaleBadge = ({ textContent, badgeColor }) => { return ( <Badge className={`bg-${badgeColor}-200 hover:bg-${badgeColor}-300 animate-pulse align-middle ml-2`} variant="secondary"><Pe ...

"Passing an Empty String as Input in a NodeJS Application

app.post('/register',function(req,res){ var user=req.body.username; var pass=req.body.password; var foundUser = new Boolean(false); for(var i=0;i<values.length;i++){ //if((JSON.stringify(values[i].usernames).toLowerCase==JSON. ...

Changing the old state in React js: A step-by-step guide

I have a collection of Faq elements. Clicking on a question should display the answer for that specific question while hiding all other answers. The issue I'm facing is that even though it displays the answer for the clicked question, it fails to hi ...

Error encountered: Jquery - function is not defined

Currently, I am developing a widget that is integrated into a client's website and it loads a jQuery file. However, we need to check if jQuery is already loaded on the client's page to prevent any conflicts, in which case we would not load our ow ...

Ways to trigger the onclick event from different controls

I have a videojs player and a button on my html page. The videojs player supports the functionality to pause/play the video when clicked. I want to trigger this event by clicking on my button. How can I achieve this? Here is the code that I tried, but it ...

A guide to sending props to a CSS class in Vue 3

I need to develop a custom toast component that includes a personalized message and class. While I have successfully passed the message as props, I am encountering difficulties in applying the bootstrap class. Component File: Toast.vue <script ...

Looking to convert a jQuery function to plain JavaScript code?

Struggling with my homework, I must apologize for any mistakes in my English. My task involves creating a chat using node.js and I found some code snippets on a website "" which I used successfully. The issue now is that the chat relies on old jQuery libr ...

The v-select menu in Vuetify conceals the text-field input

How can I prevent the menu from covering the input box in Vuetify version 2.3.18? I came across a potential solution here, but it didn't work for me: https://codepen.io/jrast/pen/NwMaZE?editors=1010 I also found an issue on the Vuetify github page t ...

You are unable to select the element in IE if there is an image in the background

Apologies for coming back with the same question, as I realize now that I was not clear in my explanation yesterday. You can find the codepen here (please note that it may not open in IE8). My issue is with dragging the 'move-obj' element in IE b ...

Unable to transfer Vue.js components in and out of the project

I have a directory structured like this. VueTree components Classic.vue Modern.vue index.js The Classic and Modern components consist of a template, export default {}, and a style. I am importing both of them in index.js as: import Classic ...

Is there a way to update page content without having to refresh the entire page?

My goal is to refresh specific content on a page without having to reload the entire page using JavaScript or jQuery. Since my project is built in PHP and JavaScript, I encountered this issue. Note : I want the page content to refresh when a user performs ...

Encountering an unrecoverable SyntaxError while trying to deploy a website on Netlify

When using commands like npm start, npm run build, and pm2 start server.js, everything runs smoothly without any errors. However, I encounter an issue when trying to deploy my project on Netlify. The Chrome console displays the error: Uncaught SyntaxError: ...

Retrieving information from Prismic API using React Hooks

I'm having trouble querying data from the Prismic headless CMS API using React Hooks. Even though I know the data is being passed down correctly, the prismic API is returning null when I try to access it with React Hooks. Here is my current component ...

Iterating through HTML table data using a JQuery for each loop

Currently, I have an HTML table that is structured in the following way: <div class="timecard"> <h3>tommytest</h3> <table class="misc_items timecard_list" border="0" cellpadding="2" cellspacing="0" style="margin:0 auto;"> < ...

Tips for retrieving the chosen value from a dropdown list in HTML

I'm having an issue with exporting specific values from multiple HTML tables into an excel file. My goal is to only export the selected values from each table, with each table being on a separate tab in the excel file. Currently, when I export the ta ...

Suggestions to update arbitrary content at a 5-second interval in Vue using Nuxt.js

As a Vue beginner, I am facing an issue with changing random text every 5 seconds while the page is loading. <template> <section class="container"> <h1 class="title"> Welcome {{ whois }} </h1> </section&g ...

Is the function added using Restangular's extendModel method not working properly?

I am facing an issue with a service and controller setup. Here is my service code: .factory('Car', function(Restangular) { var baseCars = Restangular.all('cars'); Restangular.extendModel('cars', function(obj) { ...

Using HTML and JavaScript allows for the video URL to seamlessly open in the default video player app on the device

Working on my mediaplayer website, I want to give users the option to choose which app to play their uploaded videos with. So far, I've attempted to implement a button that triggers this action: window.open("video.mkv", '_blank'); Howeve ...

Using Angular Bootstrap DualListbox to manage NgModel within an NgRepeat loop

In my current setup, I am utilizing the Angular Bootstrap DualListbox within an NgRepeat loop. However, I am encountering difficulties in getting the NgModel to function correctly as intended. To better illustrate my situation, I will provide a simplified ...