Angular.js使用ngOptions选择:标记optgroup

Web*_* IT 8 angularjs angularjs-ng-options

我刚刚开始使用Angular.js并对ngOptions有疑问:是否可以标记optgroup?

让我们假设2个物体 - 汽车和车库.

cars = [
    {"id": 1, "name": "Diablo", "color": "red", "garageId": 1},
    {"id": 2, "name": "Countach", "color": "white", "garageId": 1},
    {"id": 3, "name": "Clio", "color": "silver", "garageId": 2},
    ...
]
garages = [
    {"id": 1, "name": "Super Garage Deluxe"},
    {"id": 2, "name": "Toms Eastside"},
    ...
]
Run Code Online (Sandbox Code Playgroud)

使用此代码,我得到了几乎我想要的结果:

ng-options = "car.id as car.name + ' (' + car.color + ')' group by car.garageId for car in cars"
Run Code Online (Sandbox Code Playgroud)

结果选择:

-----------------
1
 Diablo (red)
 Countach (white)
 Firebird (red)
2
 Clio (silver)
 Golf (black)
3
 Hummer (silver)
-----------------
Run Code Online (Sandbox Code Playgroud)

但是我想标记"车库1","车库2"等选项组,或者甚至更好地显示车库的名称而不仅仅是车库名称.

selectangularjs.org文档没有说明optgroup的标签,但是我想通过ngOptions的一部分扩展该组,group by car.garageId as 'Garage ' + car.garageId或者group by car.garageId as getGarageName(car.garageId)- 遗憾的是它不起作用.

到目前为止,我唯一的解决方案是向汽车对象添加一个新属性"garageDisplayName",并在那里存储id +车库名称,并将其作为group by参数使用.但是每当车库名称改变时我都不想更新所有车辆.

有没有办法用ngOptions标记optgroups,或者在这种情况下我应该使用ngRepeat?

Ant*_*Chu 19

您可以getGarageName()group by不使用的情况下拨打电话as...

ng-options="car.id as car.name + ' (' + car.color + ')' group by getGarageName(car.garageId) for car in cars"
Run Code Online (Sandbox Code Playgroud)

您可能需要考虑在车库阵列中存储对车库对象的引用,而不是将车库ID存储在每辆车中.这样你可以改变车库名称,而不需要更换每辆车.而group by简单地变成...

group by car.garage.name