jayko03
jayko03

Reputation: 2481

How can I change ng-options value depends on other variable in angularjs?

I want to change dropdown menu depends on checkbox. So if checkbox is checked, display only specific item(s).

 <script>
angular.module('selectExample', [])
  .controller('ExampleController', ['$scope', function($scope) {
    
    $scope.colors=[
      {id:1, name:'black'},
      {id:2, name:'red'}, 
      {id:3, name:'white'},
    ]
    $scope.myColor = $scope.colors[2]; // red
    $scope.isFlagOn = false;

    function showFlag(){
      if ($scope.isFlagOn){
        return [$scope.colors.find(s => s.name === $scope.myColor)];
      }
      else{
        return $scope.colors
      }
    }

  }]);
</script>
<div ng-controller="ExampleController">

  <label>
     isFlagOn <input type="checkbox" ng-model="$scope.isFlagOn">
 
  
  </label>
  <br/><br/>
  <select ng-model="myColor" ng-options="color as color.name for color in $scope.showFlag() track by color.id">
    <option value="">Choose one</option>
    </select><br/><br/>

</div>

If checkbox is checked, I only want to show Red color option in here. Is it possible to use `ng-options`?
Thanks,

Upvotes: 0

Views: 49

Answers (1)

Kinglish
Kinglish

Reputation: 23654

Here's another way. You can filter your ng-options with:

ng-options="color.id as color.name for color in colors | filter:{name: isFlagOn? myColor.name : ''} "

Also, $scope is bound to your HTML - every variable in there is automatically $scope so you don't use it in the HTML, only the JS (controller for example).

angular.module('selectExample', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.colors = [{id: 1, name: 'black'},
      {id: 2, name: 'red'},
      {id: 3,name: 'white'},
    ]
    $scope.myColor = $scope.colors[2]; // red
  }]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.10/angular.min.js"></script>
<div ng-app="selectExample">
<div ng-controller="ExampleController">
  <label> isFlagOn <input type="checkbox" ng-model="isFlagOn">
  </label>
  <br/><br/>
  <select ng-model="myColor" ng-options="color.id as color.name for color in colors | filter:{name: isFlagOn? myColor.name : ''} ">
    <option value="">Choose one</option>
  </select><br/><br/>
</div>
</div>

Upvotes: 2

Related Questions