Is there a way to delete an element from a dropdown array in list2 after selecting an element from the dropdown list1 in Angular JS?

I have a requirement where I need to work with two drop-down lists that contain the same array elements. When an element is selected from list1 (part1), it should be removed from list2 (part1). Conversely, if the element is unselected in list1, it should appear back in list2.

To address this issue, I attempted the following JavaScript code:

Controller.js
$scope.list1 = [{"columnName": "part1", value: "obj1"},
                {"columnName": "part2", value: "obj2"},
                {"columnName": "part3", value: "obj3"},
                {"columnName": "part4", value: "obj4"},
                {"columnName": "part5", value: "obj5"}]

$scope.list2 = [{"columnName": "part1", value: "obj1"},
                {"columnName": "part2", value: "obj2"},
                {"columnName": "part3", value: "obj3"},
                {"columnName": "part4", value: "obj4"},
                {"columnName": "part5", value: "obj5"}]

$scope.getColumn = function(column) {
  $scope.indexOfColumn = $scope.list2.indexOf(column);
  $scope.removedColumn = $scope.list2.splice($scope.indexOfColumn, 1)
  console.log($scope.indexOfColumn, 'column index', $scope.removedColumn)
}

And here is the corresponding HTML markup:

<form>
   X-axis <select ng-model="xcolumn" ng-options="l1.columnName for l1 in list1" ng-change="getColumn(xcolumn)">
        <option value=""></option>
        </select>
  Y-axis
  <select ng-model="ycolumn" ng-options="l2.columnName for l2 in list2" ng-change="getColumn()">
    <option value=""></option>
  </select>
</form>

For further reference, you can view my implementation on this fiddle link: http://jsfiddle.net/soumyagangamwar/9ra59ptb/

In summary, the functionality involves ensuring that selecting or deselecting an element updates the contents of both lists appropriately. If any element is deselected, it should reappear in both lists. Any guidance on refining this solution would be greatly appreciated.

Answer №1

If you want to avoid using ngChange directives, consider creating a custom filter in AngularJS.

Start by making the ngModel directive more functional:

<select ng-model="xaxis" ng-options></select>
<select ng-model="yaxis" ng-options></select>

To filter out selected items from one select and show them in another, utilize a custom filter within the ngOptions directive like this:

<select ng-options="l1.columnName for l1 in list1 | onlyNotSelectedCouldShowHere">

Instead of using the long name onlyNotSelectedCouldShowHere, simplify it to just notSelected in the actual code.

To implement this functionality, create a custom filter called notSelected as part of your myApp module:

myApp
  // Custom filter creation
  .filter('notSelected', function(){
    return function(list, target) {
      if (target === undefined) return list;

      var filtered = list.filter(function(item) {
        return item.columnName !== target.columnName;
      });
      return filtered;
    }
  });

After realizing that arguments need to be passed to the filter (yaxis for x select and xaxis for y select), update the HTML accordingly:

<select ng-model="xaxis" ng-options="l1.columnName for l1 in list1 | notSelected:yaxis"></select>
<select ng-model="yaxis" ng-options="l2.columnName for l2 in list2 | notSelected:xaxis"></select>

For further information on AngularJS filters, check out an informative post titled Everything about custom filters in AngularJS by Todd Motto.

Update on 8/7/16: Modification made to show full list when value="" is selected.

myApp.filter('notSelected', function(){
  return function(list, target) {
    if (target === undefined || target === null) return list;
    
    var filtered = list.filter(function(item) {
      return item.columnName !== target.columnName;
    });
    return filtered;
  }
});

View the updated jsfiddle here.

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

Utilizing an 'onclick' confirmation function with PHP in HTML

Hey there, fellow members of the coding community! I'm currently working on a project where I need to create a menu that displays all clients with an option to delete them. When a user clicks on the delete button, I want a confirmation message to pop ...

The attempt to update several partial views using Jquery, MVC, and Json is currently malfunctioning

I am facing issues with updating multiple partial views using jQuery, MVC, and JSON. The partial views on my page are not getting updated. Below is the code for my view: Here is the code for my controller: public class GetStudentsController : Controlle ...

Express API encounters an issue with multer and body-parser as req.file is undefined

I am in the process of developing an API that will need to handle file uploads along with other GET and POST requests. To manage file uploads, I am using 'multer' while utilizing 'body-parser' for all other HTTP requests. My goal is to ...

What is the top choice for creating a cutting-edge front-end web module?

Which generator or scaffold is recommended for creating a contemporary front-end web module using npm/webpack? ...

"Troubleshooting issue with jQuery failing to identify PHP variable within an if

I have managed to implement a code that utilizes jQuery and PHP session to add items to the cart. Everything is working smoothly except for displaying the status of the action, such as "Added to cart" or "Updated". The message about the status is stored in ...

Display the mobile app download prompt exclusively on mobile devices and tablets

My company offers both a website and Native App for iOS & Android. Request I am looking to display a Modal dialog layer specifically on Mobiles and tablets when users access the site on these devices, prompting them to download our native app. Challenge ...

Steps for updating a value in a JSON file using PHP

Trying to modify a value within a JSON file for a specific object is throwing me off balance. The issue arises from having multiple siblings in the same JSON file sharing identical key-value pairs. The JSON structure I'm dealing with appears as follo ...

What causes a significant influx of packages each time I execute the command `npm install`?

https://i.sstatic.net/a3BxV.png https://i.sstatic.net/dcVXS.png Could this be related to my overall package.json file? ...

Utilize FormData by passing it to a separate function and then utilizing it

I have encountered a perplexing issue with my Flask app that involves submitting a form to upload an image to the server. Despite my efforts, I have been unable to find a solution on my own. When I submit the form, I use FormData to create the necessary o ...

Steps to Verify if Cookie is Turned Off in a Next.js Application

I have encountered an issue with my Next.js App. It seems to be functioning properly until I disable cookies in the browser. Is there a way for me to determine if cookies are disabled in the browser and display a corresponding message? I attempted to check ...

Having trouble with your Facebook pixel setup - is it a coding issue?

After successfully setting up our Facebook pixel using Google Tag Manager, I encountered an error message while using the "Google Pixel Helper" Chrome plugin to check the pixel. Even though I copied and pasted the code directly from Facebook, the error pe ...

There was an uncaught error in AngularJS stating that the URL in the HTTP request configuration must be a string

I've been working on a web application and have encountered some challenges. One particular issue I'm struggling with is related to the following code snippet: this.bookSpace = function (date, spaceId) { swal({ title: "Are you sure?", t ...

Efficiently calculating multiple sums of objects with d3.js

My current object structure is: { [ { id: "AL01", list: [ { speed : 5 value : 10} , { speed : 7 value : 15} ] }, { id: "AB01", ...

{ error: unable to update backend column due to invalid input syntax for integer: "undefined"}

Using a combination of postgresql database, expressJs, and react, I am currently looking to update a specific column called inCart within my database. I have implemented a fetch function that utilizes a PUT method and is triggered by an onClick event. Howe ...

Updating only partial sections of a mongo object

I have a JSON document stored in MongoDB that has the following structure: { "_id" : "cfqjJW8WZprDSJEop", "rName" : "z1", "pName" : "P-4", "ipAddress" : "21.1.1.12", "misc" : { "createdBy" : "admin", "updatedBy" : "admi ...

Animating Text Around a Circle Using HTML5 Canvas

Can someone please help me figure out what is wrong with this code? It's not rotating as it should, and the text looks messed up. I've been trying to solve this problem for hours but can't seem to get it right. function showCircularNameRot ...

Guide to running code repeatedly in node.js

Is there a way to repeat the console.log function 5 times in Node.js using the 'repeating' npm package? I am working on a node application that needs to run a specific code multiple times, but I can't seem to figure out how to achieve this. ...

Utilize AJAX response to mark checkbox as checked

I have an HTML checkbox that I am attempting to check using a script received as an ajax response. Below is my HTML snippet: <form class="form-vertical sms-settings-form"> <div class="form-group"> <div data-toggle="tooltip" titl ...

Accessing a specific JSON field in the JavaScript console

Having trouble extracting the value of StatusDescription from this JSON data structure. Despite multiple attempts, the result returned is consistently undefined. Below is a snippet of the JSON data: { "meta": { "a2": 200, &qu ...

Understanding the Process of Accessing Array Values in Immutable.js

I'm feeling a little puzzled and struggling to figure this out. Let's say I have the following code: const AnObj = Immutable.Map({ a : "a", b : Immutable.List.of( a, b, c, Immutable.Map({ a : "a" }) ) }); When working with Immu ...