简体   繁体   中英

AngularJS: ng-options add only one each of possible field values

Say I have an array like the one in the AngularJS ngOptions documentation

[
  {name:'black', shade:'dark'},
  {name:'white', shade:'light', notAnOption: true},
  {name:'red', shade:'dark'},
  {name:'blue', shade:'dark', notAnOption: true},
  {name:'yellow', shade:'light', notAnOption: false}
];

using...

<select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">

produces...

dark  
  black  
  red  
  blue
light  
  white
  yellow

I would like to filter values by dark and light, so I would like just...

dark  
light

Is it possible using ng-options to accomplish this?

use filter like this

 <select ng-model="myColor" ng-options="color.shade for color in Colors | unique:'shade'"></select>

add AngularJS filter with 'unique'

app.filter('unique', function () {
return function (input, key) {
    var unique = {};
    var uniqueList = [];
    for (var i = 0; i < input.length; i++) {
        if (typeof unique[input[i][key]] == "undefined") {
            unique[input[i][key]] = "";
            uniqueList.push(input[i]);
        }
    }
    return uniqueList;
   };
 });

You could try adding a custom filter like Alex says, or might be able to get away with a default filter like this (if you only want to show dark or light colours in the select ):

<select ng-model="myColor" ng-options="color.name group by color.shade for color in colors | { color: { shade: shadeModel }}">

Where shadeModel could be ' ', 'dark' or 'light'

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