angularjsng-options

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>

Solution

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