AngularJS - Using filters to extract specific options from multiple <select> components

There are N "select" components generated based on JSON data, with the "options" populated by an external API. I am trying to implement a custom filter that ensures when an option is selected in one "select" component, it should not appear in the other components. However, I have been unsuccessful so far.

.filter('exclude',function(lodash) {

        //@param itemsArray: array of items 
        //which fills the options of the select component.

        //@param selectedItem: the selected <option>
        //from one of the <select> components.
        return function(itemsArray, selectedItem) {
            var output = itemsArray,
                filteredItemsArray  = [];

            if(selectedItem) {
                var idx = lodash.findKey(itemsArray, { name: selectedItem.name });
                filteredItemsArray.push(selectedItem[idx]);
                output.splice(idx, 1);
            }
            return output;
        }
    });

This is the intended behavior in the HTML:

<select ng-option="p in publi track by $index | exclude: pSelect[$Index])" ng-model="pSelect[$Index]">
     <option val="usa" selected>USA</option>
     <option val="arg">Argentina</option>
     <option val="col">Colombia</option>
     <option val="cnd">Canada</option>
<select>

<select ng-option="p in publi track by $index | exclude: pSelect[$Index])" ng-model="pSelect[$Index]">
     <option val="arg" selected>Argentina</option>
     <option val="col">Colombia</option>
     <option val="cnd">Canada</option>
 <select>

<select ng-option="p in publi track by $index | exclude: pSelect[$Index])" ng-model="pSelect[$Index]">
   <option val="col" selected>Colombia</option>
   <option val="cnd">Canada</option>
<select>

I attempted this approach, but it only removes the item from the array without selecting it. What should I do?

Answer №1

It seems like what you're wanting to achieve is the filtering out of other pSelect values, which can be done by providing two arguments - pSelect and the current index.

You would then proceed to filter out values that are present in pSelect except for the current index.

An example implementation could look something like this:

ng-option="p in publi track by $index | exclude: pSelect :$index"

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

Referencing another component in StyledComponents

I'm looking to modify the properties of my parent component's :after selector whenever the child element is focused. It seemed straightforward at first, but for some reason, I just can't seem to make it work. Here's a glimpse of my comp ...

Is it possible to dynamically change the object name using $.ajax function and pass it as a

I'm attempting to parse multiple JSON files into different objects. Here is my approach: function downloadDataSave (targetObject) { // DOWNLOAD CALCULATION BACKUP var filename, response; filename = targetObject.name + '.json' ...

Integrate JavaScript code with HTML pages

After creating a basic HTML structure that I am proud of, I encountered some challenges with getting the Javascript to function properly. I am new to working with Javascript and received some initial assistance, but unfortunately, it is no longer working. ...

Send the user to an Angular route once they have successfully authenticated with Google

I'm facing an issue with redirecting users to an Angular route. Here's the scenario: When I'm on the login page and click on Google login, I get redirected to Google for authentication. After successfully logging in, I want to be redirecte ...

sinon: Techniques for stubbing an entire class as opposed to singular methods

I am faced with a situation where I have a class that instantiates another class in my test. My goal is to stub out the entire second class, ensuring that its constructor is never invoked. Consider the following scenario: Test.js class Test { construct ...

Tips for capturing a screenshot of the ESRI Map using Angular

Is there a way to capture a screenshot of the Esri map in its current state on the UI and then convert it into a PDF for download using Angular? Below is my current .ts code, but I am open to any additional suggestions. esri-map.component.html <!-- Map ...

My goal is to eliminate unnecessary code and transfer it into its own jQuery function

Currently, I am working on optimizing my code by removing redundancies and moving sections to separate functions. //Consolidating Infotypes for filtering and checking if any option is selected if(this.$infoOptions.val() != null){ ...

AngularJS directive that offers dynamic functionality

Currently, I am working on dynamically inserting an ng-options directive within various <select> elements throughout my application. These elements have their own unique class names and other directives, such as ng-if, among others. <div ng-app=" ...

Trigger the scrolling of one div when another div is scrolled

Link to Jsfiddle I'm attempting to activate my current scroll while I am outside that scroll, specifically in #DivDet Here is the code snippet of what I have tried so far: $("div#DivDet").scroll(function () { // Still trying to figure out what ...

Tally the number of sub-labels associated with each main label

In my Angular 9 application, I am looking to separate an array based on the lable field. Within each separated array, I would like to determine the count based on the subLable field. This is the array I am working with: [ {"id":1,"socia ...

Tips for emphasizing matches within a string using JSX

I've implemented a custom autocomplete feature that suggests options based on user input. I want to highlight the characters in the suggestions list that match the input value. For example, if the suggestion list includes "alligator", "lima", and "li ...

Leveraging javascript to extract data from several input fields and dynamically incorporate them into a table

I'm currently in the process of developing a script that extracts field values and organizes them into a table for verification purposes. The challenge I face is that users have the ability to add multiple fields (up to 5), each with its own unique id ...

Using HapiJs in Node.js to communicate data back and forth with the client

I have client.js and server.js files that are used to send data to my server using ajax. I am able to successfully send the searched username, but on the server side, the domain is being received as undefined. I'm unsure if the issue lies on the clien ...

Making changes to the retrieved properties using Apollo GraphQL within a Vue.js environment

I'm trying to utilize the Moment javascript library to format a date that I retrieve through Apollo-GraphQL. My setup involves VueJS Apollo on the client side for executing graphQL queries like this: import { ALL_EVENTS } from '../constants/grap ...

Is there a way to give a model of a directive scope a dynamic name while also enabling 2-way binding?

I have a challenge where I need to dynamically pass object values into a directive using ng-repeat. Here's what I've attempted so far: <td ng-repeat="attr in demographicAttrs"> <yes-no name="{{ attr }}-{{ $index }}" model="ambassa ...

Checking for empty inputs using Html, JavaScript, and CSS

I need help with a form that has 6 input fields. I want to ensure all fields are filled out, and if not, display an alert message. Any suggestions on how to achieve this? Additionally, I'm experiencing difficulties implementing different font styles. ...

Unable to attach numerous parameters to the content of the request

I am encountering an issue with my code where I have two classes and need to call two separate models using two store procedures to insert data into both tables. The controller is set up like this: [HttpPost] public IHttpActionResult AddData([FromBody]ILi ...

Can anyone offer me advice on troubleshooting a failed Capifony deployment caused by a time out during the assetic:dump process?

$ cap deploy Unfortunately, the deployment process is failing and I am receiving the following error message: * executing "cd /var/www/site/prod/releases/20120831164520 && php app/console assetic:dump web --env=prod --no-debug" servers: ["site ...

What is the method for including an AngularJS expression in element.setAttribute?

How can I add an expression to an element and create a button in a service? Here is the code snippet I currently have: var element = document.createElement('div'); ... element.setAttribute('ng-attr-title', "{{isShowRegionName?'S ...

Platform error: Responses not specified for DIALOGFLOW_CONSOLE

I've been struggling with this issue for almost a day now and I'm at a loss for what else to try. For some reason, Dialogflow Fulfillment in Dialogflow ES is refusing to make any HTTP calls. Every time I attempt, I receive the same error message ...