Jack Johnson
Jack Johnson

Reputation: 1525

How to filter ng-options on AngularJS select?

I have something like this,

<select ng-model="person"
        ng-options="person.name for person in mv.people">

Now the people array has some members that I want to hide. example:

{
   name: 'john',
   hide: true
}

How do I make sure these people aren't rendered as an option?

Upvotes: 1

Views: 1847

Answers (2)

Adrian Pop
Adrian Pop

Reputation: 1967

The easiest way is to use the filter clause like this: ng-options="person.name for person in people | filter:{hide:'false'}". In the future, you can also create a custom filter for your array and apply it in the ng-options clause. Below you have a working example.

Cheers!

var app = angular.module("myApp", []);

angular.module("myApp").controller("myController", function($scope) {
    $scope.people = [{
       "name": "john 1",
       "hide": false
    }, {
       "name": "john hidden",
       "hide": true
    }, {
       "name": "john 2",
       "hide": false
    }]
});

angular.module("myApp").filter('hidden', [function() {
    return function (object) {
        var array = [];
        angular.forEach(object, function (person) {
            if (!person.hide)
                array.push(person);
        });
        return array;
    };
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myController">
<select ng-model="person2" ng-options="person.name for person in people | filter:{hide: false}"></select>
<select ng-model="person2" ng-options="person.name for person in people | hidden"></select>
</div>

Upvotes: 0

Lex
Lex

Reputation: 7194

You can apply a filter just as you would if you were using ng-repeat.

angular.module('app', [])
  .controller('ctrl', ($scope) => {
    $scope.persons = [{
      name: 'John',
      hide: true
    }, {
      name: 'Jane',
      hide: false
    }, {
      name: 'Jeff',
      hide: false
    }, {
      name: 'Jim',
      hide: true
    }];
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <select ng-model="selectedPerson" 
          ng-options="person as person.name for person in persons | filter:{hide: false}">
  </select>
</div>

Upvotes: 2

Related Questions