Search code examples
javascriptangularjsangularjs-select

How to disable the selected option from other select list in angularjs?


I am setting up a select list From Year and To Year through ng-repeat and its working fine what I need is when I select an option from the list it should be disabled from another list. how to do using Angularjs?

Thank You.

HTML

<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>

JSON

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

Solution

  • Run the following snippet and let me know, is this what exactly you want

    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>