AngularJS: Filtering one array with another array

I have a data structure structured in the following way:

$scope.data = [
  {
    title: "Title1",
    countries: ['USA', 'Canada', 'Russia']
  },
  {
    title: "Title2",
    countries: ['France', 'Germany']
  }
];

Each item contains an array of country names.

The data is displayed as follows:

<tr ng-repeat="dataItem in data">

I would like to allow users to filter this list by entering a list of countries in an input field:

How can I achieve this?

Currently, I have implemented something similar to this:

  <input ng-model="searchFilter.countries">
   ...
  <tr ng-repeat="dataItem in data | filter: searchFilter: true">

However, this only works for one country and not for arrays of countries listed in the input separated by commas.

Answer №1

Here's a straightforward approach without the need for a custom filter:

HTML:

<input ng-model="selectedCountries" ng-list>

<tr ng-repeat="item in items | filter:countryFilter">

JS:

$scope.countryFilter = function(item) {
    if (!$scope.selectedCountries || $scope.selectedCountries.length < 1)
        return true;
    var foundMatch = false;
    $scope.selectedCountries.filter(function(country) {
        foundMatch = foundMatch || item.countries.indexOf(country) != -1
    });
    return foundMatch;
};

VIEW DEMO HERE

Answer №2

Check out the example I made here.

This code utilizes the ngList directive as suggested by Zahori and includes a custom filter for countries.

myApp.filter('CountryFilter', function() {
    return function(items, countries) {
        if (!angular.isUndefined(items) && !angular.isUndefined(countries) && countries.length > 0) {
            var filtered = [];

            angular.forEach(items, function(item) {
                angular.forEach(countries, function(currentCountry) {
                     if(item.countries.indexOf(currentCountry) >= 0 ) filtered.push(item);
                });

            });

            return filtered;
        } else {
            return items;
        }
    };
});

Answer №3

Your Input must be formatted as a String, not an Array. To achieve this, consider utilizing ngList.

For guidance on how to implement ngList effectively, refer to the following helpful example: https://docs.angularjs.org/api/ng/directive/ngList

Answer №4

Make sure to implement the searchFilter as a method within your $scope object. This will allow you to customize the logic and not just default to searching by string only.

$scope.searchFilter = function (dataItem) {
    // Add your custom search logic here and return true/false accordingly.
};

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

Ways to refine data using multiple criteria

I have a list of alarm data that I need to filter based on specific conditions. If there are multiple alarms of type "pull_Alarm" and "emergency_alarm" in the same location, I want to prioritize the "emergency_alarm". Here is my list: [ { ...

The functionality of Bootstrap Scrollspy seems to be malfunctioning as it fails to navigate or scroll through the content

I've been struggling to get ScrollSpy up and running. I have a fixed menu on the left side that sticks as the user scrolls down, but for some reason, ScrollSpy just won't cooperate. I've tried numerous methods to make it work, even with the ...

Entity Framework AJAX Delete Functionality Fails to Operate

I'm puzzled as to why this isn't working. Here's the code: View <input type="button" value="Delete" onclick="deletefunction(@item.PhotoId)"/> Controller [HttpPost] public ActionResult Delete(int photoid) { var imgDelete = db.Ph ...

Splitting a JavaScript string into a two-dimensional array

Can someone assist me with splitting a string into a two-dimensional array? This is an example of my input array: var str = 'a) first sentence without fixed length b) second phrase c) bla bla bla' The desired output array should look like this ...

Feeling lost when it comes to forms and hitting that submit button?

Below is a sample form structure: <html> <head> <title>My Page</title> </head> <body> <form name="myform" action="http://www.abcdefg.com/my.cgi" method="POST"> <div align="center"> <br><br; <br& ...

Steps for executing the function in the specifications - Protractor

My script is written within the following module: var customSearch = function () { this.clickSearch = function (value) { element(by.id('searchbutton')).click(); }; this.waitElementFound = function (value) { var EC = protractor.Ex ...

Include a class in ul > li elements upon page load in Angular4

I attempted to add a class to each "li" element in an Angular4 page, but the class was not applied. Here is the relevant HTML code: <ul class="pagination"> <button class="previous" (click)="previous()">Previous</button> <button ...

Interested in building an album app using Django Tastypie and Backbone?

I'm currently working on developing a new album application using django, with two essential django models: class Album(models.Model): name = models.CharField(max_length=100) family = models.ForeignKey(FamilyProfile) created_by = models.F ...

Error in executing test case with NodeJs, express, and MongoDB with Jest

Original Post Link Read the Original Post Situation I am currently attempting to test the functionality of my GET endpoint route. I have confirmed that the route is set up correctly by running my server, but when I try to implement a test case, I enco ...

Switching image sources using jQuery on click

Take a look at the code snippet I've assembled below: $('img').on({ 'click': function() { var src = ($(this).attr('src') === 'memes/2a.png') ? 'memes/2b.png' : ...

Removing a MongoDB record when a URL is accessed using node.js

Currently, I am developing a Twitter replica for a project using node.js and express. Tweets are being stored in MongoDB. One of the functionalities I am working on is allowing users to delete their tweets. The idea is to have a button or link under each ...

What is the best way to arrange an array of objects based on a specific attribute?

Ordering object based on value: test": [{ "order_number": 3, }, { "order_number": 1, }] Is there a way to arrange this so that the object with order_number 1 appears first in the array? ...

Exporting JSON data to an Excel file using an array of objects with embedded arrays

I am currently developing a fitness application that allows users to create workout routines and download them as an excel file. The data is structured as an array of objects, with each object representing a workout date and containing details of the exerc ...

Leveraging an HTML interface in conjunction with a node.js application

My objective is to implement JavaScript on the server side. To achieve this, I have decided to use node.js as it seems like the most logical solution. While I am quite familiar with node.js from working on applications, I now need to utilize it for server- ...

Tips for creating a filter in React JS using checkboxes

In my current situation, I have a constant that will eventually be replaced with an API. For now, it resembles the future API in the following way: const foo = { {'id':1, 'price':200, 'type':1,}, {'id':2, &apo ...

What is the best way to show an array within a string using javascript?

Take a look at this code snippet : const names = ["Alex", "John", "Kit", "Lenny"]; for(let i = 0; i < 4; i++) { $("body").append("<p>" + names[i] + "</p>'); }; Can you figure out how to dynamically add each item in the 'names&a ...

The system has encountered an issue: "EntityMetadataNotFound: Unable to locate metadata for the entity named 'User

Just wanted to reach out as I've been encountering an issue with my ExpressJS app recently. A few days ago, everything was running smoothly without any errors. However, now I'm getting a frustrating EntityMetadataNotFound: No metadata for "User" ...

Transform the Jquery code for filtering a list based on checkboxes to Vanilla JavaScript

Looking to convert a code snippet that filters a list based on data attributes from jQuery to JavaScript. $('.checkbox').change(function() { $('li.list').each(function(i, item) { var color = $(this).data('color'); ...

Updating WordPress div content based on selected post type using dropdown menu

I am in the process of developing a WordPress plugin that will generate a custom post type and widget for users to add to their websites. The goal is to have the widget display a dropdown select box with titles of each post, and when a title is selected, t ...

Ways to customize the color of a cell in fullcalendar

I'm having trouble changing the color of AngularUI's calendar cells. Currently, I can only change the event color. How can I modify the color of the day cell? Below is my Angular code for defining events: $scope.events = [ {className: &ap ...