user1576738
user1576738

Reputation: 121

ng-options filter with condition

I have a select with ng-options + filter and need to apply a condition to the filter itself. So if a specific condition is met then apply the filter otherwise don't. Thanks in advance.

# example
if (elb_vm.elbInstances[index]['new_record?']){
   apply ng-options filter.
 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<section ng-app="myApp">
  <div ng-controller="AppCtrl">
    <select ng-model="selected" 
      ng-options="('Subnet: ' + type) for type in types | filter: '!public' : true">
    </select>
  </div>
</section>

Upvotes: 0

Views: 752

Answers (1)

palaѕн
palaѕн

Reputation: 73956

You can use two select elements, one with filter and other without filter and show them based on ng-if like:

ng-if="elb_vm.elbInstances[index]['new_record?']"

Demo:

var app = angular.module('myApp', []);
app.controller('AppCtrl', function($scope) {
  $scope.selected = "";
  $scope.condition = false;
  $scope.types = ["publicExtra","public","private"];
  
  $scope.toggleCondition = function(){
    $scope.condition = !$scope.condition;
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<section ng-app="myApp">
  <div ng-controller="AppCtrl">
    <button ng-click="toggleCondition()">Toggle Condition</button> {{ condition }}<br><br>
    <select ng-model="selected" ng-if="condition"
      ng-options="('Subnet: ' + type) for type in types | filter: '!public' : true">
    </select>
    <select ng-model="selected" ng-if="!condition"
      ng-options="('Subnet: ' + type) for type in types">
    </select>
  </div>
</section>

Upvotes: 1

Related Questions