Reputation: 2481
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>
Upvotes: 0
Views: 49
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