Applying various Angular filters to an array of objects within HTML select elements

I'm fairly new to working with JS and the rather challenging learning curve of AngularJS. I have an array containing numerous objects with the relevant properties listed below:

  $scope.myRecs = [{country: 'Ireland', city: 'Dublin', type: 'Food'},
                {country: 'Italy', city: 'Rome', type: 'Activity'}, 
                {country: 'Australia', city: 'Sydney', type: 'Bar/Pub'}];

The goal is to display the array in the following format:

<div ng-repeat="rec in myRecs"></div>

The aim is to filter the array using three Ionic HTML select elements (one for each property) with options structured like this:

<select ng-model = "selectedCountry">
    <option value="All"></option
    <option ng-repeat="rec in myRecs | orderBy: 'country' | unique: 'country'">{{rec.country}}</option>
</select>

<select ng-model = "selectedCity">
    <option value="All"></option>
    <option ng-repeat="rec in myRecs | orderBy: 'city' | unique: 'city'">{{rec.city}}</option>
</select>

<select ng-model = "selectedType">
    <option value="All">All</option>
    <option ng-repeat="rec in myRecs | orderBy: 'type' | unique: 'type'">{{rec.type}}</option>
</select>

Note: Duplicates in the select options have been removed using the unique filter from the angular-filter library.

To filter each select option based on the choices made in the other two select options, various filtering methods have been attempted such as:

<select>
    <option ng-repeat="rec in myRecs | orderBy: 'type' | unique: 'type' | filter: selectedCountry && selectedCity">{{rec.type}}</option>
</select>

And utilizing different syntaxes like:

filter: {city:selectedCity,country:selectedCountry}

or

filter: selectedCity || selectedCountry

or

filter: selectedCity | filter: selectedCountry

The correct syntax and approach remain unclear. Similarly, attempts have been made to filter the displayed array using syntaxes like:

<div ng-repeat="rec in myRecs | filter: selectedCountry && selectedCity && selectedType"></div>

or

<div ng-repeat="rec in myRecs | filter: selectedCountry || selectedCity || selectedType"></div>

etc...

The outcomes are puzzling. Selecting a country filters the city options but leaves the type options empty. It seems that while it may work with two filters, involving three leads to issues. Furthermore, if a type is chosen first, the subsequent selects return no results :/

Is this the right method for filtering the array or could there be a more efficient approach?

For the All options, what value should be assigned to prevent them from affecting the array when selected?

Thank you!

Answer №1

Here is a simple example demonstrating how it can be done:

<select ng-model="selected.country">
    <option value="">All</option>
    <option ng-repeat="rec in myRecs | filter: {city: selected.city, type: selected.type}">{{rec.country}}</option>
</select>
<select ng-model = "selected.city"> 
    <option value="">All</option>
    <option ng-repeat="rec in myRecs | filter: {country: selected.country, type: selected.type} ">{{rec.city}}</option>
</select>
<select ng-model = "selected.type"> 
    <option value="">All</option>
    <option ng-repeat="rec in myRecs | filter: {country: selected.country, city: selected.city}">{{rec.type}}</option>
</select>

View the working jsFiddle here.

Please note: The unique filter has been removed to simplify this example.

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

What is the method to adjust the anchor point for a MUI popover?

I currently have the following code for handling a popover: const [open, setOpen] = useState(false); const anchorRef = createRef() const handleClose = () => { setOpen(false); }; const handleClick = useCallback( (event: MouseEvent<H ...

What is the jquery alternative to the PHP 'if IP equals' condition?

I am curious to know if the following PHP 'if' conditions can be achieved in jquery or JavaScript, with a preference for jquery. if ($_SERVER['REMOTE_ADDR'] != '123.99.55.616') { // public doingness } if ($ ...

Issue with jQuery Master-Detail dropdown list selection

Having trouble isolating the code in this jsfiddle script. Despite my efforts, it seems that isolation is not working as expected and Firebug isn't showing any errors on the console: <!DOCTYPE html> <html lang="en"> <head> ...

Reduce the size of a container element without using jquery

In my Angular application, I have structured the header as follows: -- Header -- -- Sub header -- -- Search Box -- -- Create and Search Button -- -- Scroll Div -- HTML: <h1> Header </h1> <h3> Sub header </h3> <div class="s ...

What is the best location for setting up Angular with Apache?

Before anything else, I want to clarify that my query does not involve the installation process of Angular. As a beginner with this framework, I already have a question right from the start. Typically, I develop new web projects (HTML, PHP...) in the apac ...

JavaScript and CSS failing to implement lazy loading with fade-in effect

Is there a way to add the fade-in animation to an image when it is loaded with JavaScript or CSS? Currently, the code I have only fades in the image once it is 25% visible in the viewport. How can I modify it to include the fade effect upon image load? ...

Remove an item from a complex JSON structure based on the specified name. The function will then return the

Hey there, I'm just starting out with react native and I have an array of objects. My goal is to remove an inner object from this JSON data. [ { Key: 1, exchnageArr: [ { name: ”FX” }, { name: ”MK” ...

Instructions on incorporating a logical condition for an object that is entering a region in motion

I am currently in the process of developing a new game concept. The goal of the game is to maneuver a square across the screen while avoiding raindrops that fall from the top of the canvas. I need assistance with programming the logic so that when a rain ...

Is the AngularJS `$http` cache capable of storing server errors in its cache?

When working with Angular, using $http.get(url, {cache:true}) will cache server responses for easy access. But what happens when the GET request to the server fails? This could be due to a temporary connection issue or a server response such as a timeout. ...

I am in the process of creating a dropdown menu for a navbar that will appear when the cursor hovers over a specific element, complete with an arrow pointing upwards

In my current project with NextJS and Tailwind CSS, I've successfully created a dropdown menu but I'm facing an issue with positioning the arrow to point to the specific element being hovered on. In a previous version, I tried rotating a div at 4 ...

Converting a nested JavaScript array into a PHP array

Having a javascript array is how my dilemma starts: foodList = ([apple,10,],[banana,20]) To convert this to a json object and send it to php, I perform the following action: var jsonData = JSON.stringify(foodList); The challenge now is extracting values ...

What is the best way to add 1 to a number every second with javascript?

My code seems to be functioning correctly, but I'm having trouble setting the delay and stopping the increment after a certain interval. Can someone please assist me with this? Javascript: $(document).ready(function() { var number = parseInt($(& ...

Is there a way to update the Angular component tag after it has been rendered?

Imagine we have a component in Angular with the selector "grid". @Component({ selector: 'grid', template: '<div>This is a grid.</div>', styleUrls: ['./grid.component.scss'] }) Now, when we include this gri ...

Exploring the `React.createRef` method using Enzyme for testing purposes

Is there a way to test the following class that utilizes the React.createRef API? I couldn't find any examples online. Has anyone attempted this before? How can I mock the ref effectively? My preference would be to utilize shallow. class Main exten ...

Transfer information from an array to a Vue function

Having some difficulties passing data to the function myChart within the mounted section. As a beginner in vuejs, I'm struggling with identifying the issue. I am trying to pass data in labels and datasets, which are called from my function. Can anyone ...

Adjusting the properties of an element with Javascript

My goal is to dynamically set the value of a parameter within a <script> element using JavaScript. I am using the Stripe checkout.js and I want to populate the Email input field with a value obtained from another text box on the page. Here's how ...

What could be the reason for a variable not being assigned a value following the xmlhttp.responseText?

During the validation process of a send-fax form, I am checking if a fax has been previously sent using our software fax package. This involves a simple query to a table executed by a script, which will return text if a previous fax exists or blank if not. ...

Tally of number series in an array

If my array looks like [0, 2, 4, 10, 10, 10, 10, 2, 5, 3, 2, 10, 10, 5, 7, 4, 10, 10, 10, 10] How do I determine the number of times a sequence of 10's occurs with at least 3 repetitions. In this example, the output would be 2 because there are 2 s ...

Is my front-end JavaScript fetch request mistakenly being sent as a GET instead of a POST?

On clicking the submit button, a fetch request is triggered. Strangely, in the developer tools, it shows up as a GET request. I tested the request using Insomnia and it returned the handlebars site to me without any of my console logs appearing on either ...

Tips for retrieving the chosen value from an ajax.net ComboBox using javascript

Is there a way to extract the selected value from an ajax.net combobox using JavaScript for client-side validation? What would be the most effective method to achieve this? Thank you. This is how I managed to obtain the value: var combo = $get('ddl ...