如何在AngularJS select上过滤ng-options?

时间:2018-12-06 22:57:44

标签: html angularjs angularjs-ng-options

我有这样的东西

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

现在people数组中有一些我想隐藏的成员。例如:

{
   name: 'john',
   hide: true
}

我如何确保这些人没有被选拔?

2 个答案:

答案 0 :(得分:2)

您可以像使用filter一样应用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>

答案 1 :(得分:0)

最简单的方法是像这样使用filter子句:ng-options="person.name for person in people | filter:{hide:'false'}"。将来,您还可以为数组创建自定义过滤器,并将其应用于ng-options子句中。下面有一个有效的示例。

干杯!

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>