Display a dropdown list using ng-repeat to prevent selecting the same value multiple times

Within my ng-repeat loop, I have a drop-down menu and an add button that allows users to add new drop-down menus to the list. However, I am looking for a way to restrict the second drop-down menu from selecting the same value as the first one. In other words, I want to prevent the second drop-down menu from selecting the same value that has already been selected in the first drop-down menu.

Pankaj Parkar provided an answer to a similar question of mine, but I am struggling to implement it in my JSFiddle code.

ng-repeat="post in posts | filter: { type: selectedValue }"

I would greatly appreciate any assistance with this issue.

Original question can be found here.

Link to my JSFiddle.

var app = angular.module('angularjs-starter', []);

  app.controller('MainCtrl', function($scope) {
  
  $scope.names = ['Mobile','Office','Home'];

  $scope.choices = [{id: 'choice1'}];
  
  $scope.addNewChoice = function() {
    var newItemNo = $scope.choices.length+1;
    $scope.choices.push({'id':'choice'+newItemNo});
  };
  
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="angularjs-starter" ng-controller="MainCtrl">
   <fieldset ng-model='y' ng-repeat="choice in choices">
      <select>
         <option ng-model='x1' ng-repeat = "x in names">{{x}}</option>
      </select>
   </fieldset>
   <button class="addfields" ng-click="addNewChoice()">Add fields</button>
</div>

Answer №1

Ensure that your options are placed within the items array to properly scope them. The results should be retrieved from the choices array.

var app = angular.module('angularjs-starter', []);

app.filter("itemFilter", function(){
  return function(items, choice){
    filtered_items=[];
    for(var i=0;i<items.length;i++){
      if(items[i].choiceID==null || items[i].TYPE_ID==choice.TYPE_ID)
        filtered_items.push(items[i]);
    }
    return filtered_items;
  }
});

app.controller('MainCtrl', function($scope) {
  
  $scope.items = [
     {"TYPE_ID":1,"TYPE_NAME":"Jpeg"},
     {"TYPE_ID":2,"TYPE_NAME":"Odt"},
     {"TYPE_ID":3,"TYPE_NAME":"docx"},
     {"TYPE_ID":4,"TYPE_NAME":"xls"}
  ];

  $scope.choices = [];
  
  $scope.addNewChoice = function() {
    var newChoiceID = 'choice'+$scope.choices.length+1;
    for(var i=0;i<$scope.items.length;i++){
    if($scope.items[i].choiceID==null){
      $scope.items[i].choiceID = newChoiceID;
$scope.choices.push({'id':newChoiceID,TYPE_ID:$scope.items[i].TYPE_ID});
        break;
      }
    }
  };

  $scope.updateValue = function(choice) {
    for(var i=0;i<$scope.items.length;i++){
    if($scope.items[i].choiceID==choice.id)
      $scope.items[i].choiceID = null;
    if($scope.items[i].TYPE_ID==choice.TYPE_ID)
      $scope.items[i].choiceID = choice.id;
    }
  };
  
  $scope.addNewChoice();
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
<div ng-app="angularjs-starter" ng-controller="MainCtrl">
   <fieldset ng-repeat="choice in choices">
      <select ng-model="choice.TYPE_ID" ng-change="updateValue(choice)">
         <option ng-repeat = "item in items | itemFilter:choice" value="{{item.TYPE_ID}}">{{item.TYPE_NAME}}</option>
      </select>
   </fieldset>
   <button class="addfields" ng-show="items.length>choices.length" ng-click="addNewChoice()">Add fields</button>
   <h4>Data for backend</h4>
   <ul>
     <li ng-repeat="choice in choices">TYPE_ID: {{choice.TYPE_ID}}</li>
   </ul>
</div>

Answer №2

Give this solution a try, it is based on the initial value of the first options selected. Feel free to modify it according to your needs.

var app = angular.module('angularjs-starter', []);

  app.controller('MainCtrl', function($scope) {
  
  $scope.names = ['Mobile','Office','Home'];
  $scope.selectedValue = [];
  $scope.choices = [{id: 'choice1', options: $scope.names}];
  
  $scope.addNewChoice = function() {
    var newItemNo = $scope.choices.length+1;

    // Initial Frame options list
    var ele = document.getElementById('myOptions');
  var angularEle = angular.element( ele );
        
    var value = angularEle[0].value;
    $scope.selectedValue = $scope.names.filter(item => item !== value)
   
    $scope.choices.push({'id':'choice'+newItemNo, options: $scope.selectedValue});
  };
  
});
.addfields {
    -webkit-appearance: button;
    cursor: pointer;
  color: #fff;
    background-color: #337ab7;
    border-color: #2e6da4;
  
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js"></script>
<div id='mainC' ng-app="angularjs-starter" ng-controller="MainCtrl">
   <fieldset ng-model='y' ng-repeat="choise in choices">
<p> <ul>Id, Options
<li ng-repeat="(k,v) in choise">{{v}}</li>
</ul></p>
    
<select id='myOptions'>
      <option ng-model='x1' ng-repeat = "x in choise.options">{{x}}</option>
   </select>
   </fieldset>
   <button class="addfields" ng-click="addNewChoice()">Add fields</button>
</div>

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 best way to change the response URL in an AJAX function?

I have a function using ajax that redirects to the response from a specified URL upon success: document.getElementById("button1").addEventListener("click", function (e) { e.preventDefault(); $.ajax({ url: 'http://localhost:8080/someLo ...

Tips for displaying autocomplete suggestions as clickable links?

I am new to using Ajax and trying to figure out how to display autocomplete results as clickable links. I have managed to list the related results, but I am struggling to add the links. I believe the links need to be added within the script as an HTML tag. ...

Properly handling curves in THREE.JS to ensure efficient disposal

I am facing a challenge with managing memory in my project. I have a dynamic sphere with moving points on it, and I am creating curves to connect these points. Here is an illustration of the process: https://i.sstatic.net/PGWuU.jpg As the points are cons ...

Unlocking the Chrome performance tool summary using SeleniumDiscovering the Chrome performance tool

I'm looking to utilize the Chrome performance tool for analyzing my website and then extract a summary of the results using Selenium WebDriver in Java. Despite extensive searching, I haven't been able to find a suitable solution yet. To give you ...

Issue with showing Angular directive

I've been working on implementing an angular dropdown list with Bootstrap. The functionality includes a directive that allows the user to select a menu option from the dropdown and receive an alert message. To see the implementation in action, I have ...

The behavior of Material-UI Drawer varies when used on tablets

Encountering some strange issues with the Material-UI drawer component. It's scrolling horizontally on my iPad, while it scrolls vertically on my MacBook and Android Phone. Expected Result on MacBook: https://i.sstatic.net/txBDf.png On my MacBook, it ...

Incorporating traditional Javascript classes for modeling in React development

Can traditional JavaScript classes be utilized in models within the MVC framework while using React, as opposed to relying on Redux or contexts & reducers which may impact reusability? If this approach is feasible, how can we efficiently 'subscribe&ap ...

What could be the reason for the lack of error handling in the asynchronous function?

const promiseAllAsyncAwait = async function() { if (!arguments.length) { return null; } let args = arguments; if (args.length === 1 && Array.isArray(args[0])) { args = args[0]; } const total = args.length; const result = []; for (le ...

When there is a lack of internet connection, WKWebView does not reach completion or timeout

When using a WKWebView to navigate to a local HTML page, I encountered an issue with a remote Javascript asset tag that never finished downloading. This occurred even when the iOS device was not connected to the internet or had slow internet speeds. The p ...

What is the best way to alter the order of the .map function in JavaScript to display in ascending or descending order?

I currently have 25 songs in my Spotify playlist, with the possibility of more being added in the future. The songs are numbered from 1 to 25. However, the map() function I use only displays the top 10 songs (1 to 10). When a new song is added, it is assig ...

Invoke the parent function when extending javascript prototype

Below is the Meta-Code I am currently working with: var Parent = function(){} Parent.prototype.doSomething = function(){ console.log("As a parent I did like a parent"); } var Child = function(){} Child.prototype = new Parent(); Child.prototype.doSometh ...

The instanceof operator does not recognize the value as an instance and is returning false, even though it

Is there a method to verify the current instance being used? This is what I am logging to the console: import { OrthographicCamera } from 'three'; // Later in the file: console.log(camera instanceof OrthographicCamera, camera); and the result ...

Failed: Protractor could not synchronize with the page due to an error saying "angular is not present on the window"

I encountered an issue with my Protractor test scripts where I started receiving an error message. Everything was working smoothly until I made some updates to a few scripts in my projects. The error occurs at the end of running the scripts. I attempted ...

Creating a tree array in JavaScript from JSON data

I have been struggling to create a tree array from the given JSON data. I have attempted to use filter, map, and reduce methods, but haven't been successful in achieving the desired result. [{ "code": "2", "name": "PENDING" },{ "code": "2.2", ...

Prevent scrolling while popup is open

I found a helpful tutorial online for creating a jQuery popup (). However, due to my limited understanding of jQuery, I'm having trouble getting it to meet my needs. The issues I'm facing are: I need to prevent the webpage from scrolling when ...

Is it possible for a div with fixed position to still have scrolling functionality

My fixed positioned div (#stoerer) appears to be moving while scrolling, although it is just an optical illusion. Check out this visual explanation: view gif for clarification Below is the code snippet in question: <div id="stoerer"> <button ...

Arrange and display similar objects together

I have a list of items in a listView that need to be visually grouped based on their class, displayed within boxes. For example, I have 5 items with the following classes: <div class="1"></div> <div class="1"></div> <div class= ...

The integration of AngularJS with Node.js prevents the access of Angular services in the directive link function

I am grappling with creating an Angular.js directive using NodeJS and incorporating external angular services like $parse in the directive link function. I'm facing issues as I cannot access the injected services, as they are showing up as undefined. ...

Looking for help with aligning an icon to the right side of my text

I'm struggling with aligning the icon to the right of the quantity. When I use float:right, it places the icon at the far right of the cell instead of next to the text. Is there a way to get it to be on the right side of the text but directly adjacent ...

The function Firebase.database() is unavailable in the Sails Service

I have developed a service named Firebase.js, and I am attempting to utilize it from my Controllers by using Firebase.database. However, I am encountering an error stating that Firebase.database() is not a function services/Firebase.js var admin = requir ...