Is it possible to prevent the selected option from being available in other select lists using AngularJS?

Can anyone help me figure out how to disable an option in one select list when it is selected in another using AngularJS? I have set up a select list for From Year and To Year with ng-repeat, which is working fine. Now, I just need to implement the functionality where selecting an option in one list disables that option in the other list. Any ideas on how to achieve this?

Thank you in advance!

Here is the HTML code:

<li> 
    <select class="form-control">
        <option value="" selected disabled>From Year</option>
        <option ng-repeat="option in selectedYear" >{{option.years}}</option>
    </select>
</li>

<li>
    <select class="form-control">
        <option value="" selected disabled>To Year</option>
        <option ng-repeat="option in selectedYear" >{{option.years}}</option>
    </select>
</li>

And here is the JSON data:

{"json1":"[{\"years\":2018},{\"years\":2017},{\"years\":2016},{\"years\":2015}]

Answer №1

Execute the code below and confirm if it meets your requirements

angular.module("app", [])

  .run(($rootScope) => {

    $rootScope.selectedYears = []

    $rootScope.years = [{
      "years": 2018
    }, {
      "years": 2017
    }, {
      "years": 2016
    }, {
      "years": 2015
    }]
  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="app">
  <li>
    <select class="form-control" ng-model="selectedYears[0]">
      <option value="" selected disabled>From Year</option>
      <option ng-repeat="option in years"
              ng-disabled="selectedYears.indexOf(option.years) !== -1 && selectedYears.indexOf(option.years) !== 0"
              ng-value="{{option.years}}">
        {{option.years}}
      </option>
    </select>
  </li>

  <li>
    <select class="form-control" ng-model=selectedYears[1]>
      <option value="" selected disabled>To Year</option>
      <option ng-repeat="option in years"
              ng-disabled="selectedYears.indexOf(option.years) !== -1 && selectedYears.indexOf(option.years) !== 1"
              ng-value="{{option.years}}">
        {{option.years}}
      </option>
    </select>
  </li>
</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

Shifting divs to different positions upon clicking

I am currently working on a project where I have three divs in a container positioned next to each other. My goal is to make them change their positions when clicked. For example, clicking on the left div should move it to the center position. Here is my p ...

Enhancing Kendo Grid with Checkbox Columns

I am facing a situation with my kendo grid where I need to insert two checkbox columns in addition to the existing set of columns. <script id="sectionPage" type="text/kendo-tmpl"> @(Html.Kendo().Grid<SectionPageModel>() .Na ...

The jQuery script designed to verify the page height doesn't appear to be functioning as intended

Below is a snippet of jQuery code that I'm working with: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/javascript"> hasVBar=""; hasHBar=""; $(docume ...

The server has denied access to the resource due to a HTTP 403 Forbidden error in the AJAX request

I have exhausted all resources online in an attempt to resolve an error I am encountering with my AJAX request. Even after trying XMLHttpRequest() request, the problem remains unsolved. Below is the code for my Ajax Request: $.ajax({ type: "POST", url: " ...

Can a file be transferred from an Electron application to an Express server by supplying the file path?

This is my current objective: A user drags and drops a file into Electron Electron uses a python script via child_process.exec to convert the file The conversion process generates a new file in the same directory as the original With knowledge of the path ...

What is the best way to link an image in a React Component NPM module?

I have developed a date picker component in React and I'm currently working on uploading it to NPM. The component utilizes an external SVG file, but I am encountering issues with referencing that SVG file properly. Here's the structure of my fil ...

What are your thoughts on combining a JSON object with HTML?

When using ASP.NET MVC, it is possible to return a JSONResult. return JSON(new { View = RenderViewAsString("MyView", model), wasSuccessful = true}) This approach combines HTML and data in a single JSON object. The goal is to utilize strongly typed HtmlHe ...

Error: The CommentsSection function did not return any values after rendering

I've been working on a project to create a simple web page that features multiple Material UI card components and integrates Redux to simulate a basic social media platform. The main issue I'm encountering is that when I try to expand a card, an ...

What causes an undefined outcome when a promise is fulfilled?

Could you help me understand something? const promise1 = new Promise((resolve, reject) => { setTimeout(() => { if(true) { resolve('success') } else { reject('failure') } }, 4000) }) promise1.then(resul ...

What could be causing the malfunction of my Nextjs Route Interception Modal?

I'm currently exploring a different approach to integrating route interception into my Nextjs test application, loosely following this tutorial. Utilizing the Nextjs app router, I have successfully set up parallel routing and now aiming to incorporate ...

Tips on utilizing the Material Ui Select input property?

Trying to understand why material-ui's InputBase is functional while regular HTML input is not. The documentation defines the input prop as follows: An Input element; does not have to be a material-ui specific Input. Successful example: import Sele ...

The $routeChangeSuccess event is failing to trigger in ngNewRouter in AngularJS version 1.4

Transitioning from AngularJS 1.3 to AngularJS 1.4 has brought about some changes, including the use of AngularJS's new route method known as ngNewRouter, specifically introduced in AngularJS 1.4. Below is a snippet of my code: var versionModule = ng ...

Encountering a 405 Error while attempting to perform a search on Twitter

I have been attempting to search Twitter using jQuery, but I am encountering an issue. The response only shows: https://api.twitter.com/1.1/search/tweets.json?q=django 405 (Method Not Allowed) XMLHttpRequest cannot load https://api.twitter.com/1.1/search/ ...

Unable to retrieve the updated array value in NodeJs when accessed outside the function scope

I recently started working with node and I'm attempting to retrieve the Twitter id of a group of users. The module takes an array of screen names, iterates over them to obtain the userId, and then adds them to an array. However, I'm facing an iss ...

Encountering a Sass Dart error "Bad state: Can't access parent outside of a module" while running npm start in a Create React App

My team has come across an unusual error while attempting to npm start a Create React App we are working on. The error message states: Bad state: Can't access __parent outside of a module, resulting in a failed Build process. This issue is new to us, ...

Error thrown in JavaScript when calculating the distance

I am currently working on calculating distances between two points, but I keep getting an error that says Uncaught TypeError: a.lat is not a function. function MapLocations() { var i = 0; var infoWindow = new google.map ...

Utilizing Props to Manage State within Child Components

Is it possible to assign the props received from a Parent Component as the state of a Component? export default class SomeComp extends Component { constructor(props) { super(props); this.state = someProps; // <-- I want to set the ...

"Ajax validation is causing the duplication of the HTML page content within an HTML

My PHP username validation with Ajax code seems to be duplicating my HTML page inside an HTML div element, which is used for displaying Ajax errors. Despite trying various solutions and searching on Google, I have not been able to find a resolution yet. Th ...

Tips for calculating the distance from the cursor position to the visible area

Is there a way to determine the cursor's offset from the top of a textarea's view rather than its position? While e.target.selectionStart provides the cursor position, $el.scrollTop gives the scroll offset of the textarea. Any suggestions on ho ...

Tips for Embedding React into a Specific ID using Hooks on an HTML Document

I am currently diving into the world of React hooks. While I understand class components, Hooks seem to be missing a specific render section. When adding React to a webpage (without using CREATE REACT APP), how do I specify where my hook should run on the ...