简体   繁体   中英

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?

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> 

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM