我刚刚开始使用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"},
...
]
使用此代码,我得到了我想要的结果:
ng-options = "car.id as car.name + ' (' + car.color + ')' group by car.garageId for car in cars"
选择结果:
-----------------
1
Diablo (red)
Countach (white)
Firebird (red)
2
Clio (silver)
Golf (black)
3
Hummer (silver)
-----------------
但是我想标记选择组,例如" Garage 1"," Garage 2",......或者甚至更好地显示车库的名称而不仅仅是garageId。 / p>
angularjs.org documentation for select对optgroup的标签一无所知,但我想通过部分ngOptions(例如group by car.garageId as 'Garage ' + car.garageId
或group by car.garageId as getGarageName(car.garageId)
- 扩展该群组,这可能无法正常工作
到目前为止,我唯一的解决方案是添加一个新属性" garageDisplayName"到汽车对象并存储id +车库名称,并将其作为参数分组使用。但是,每当车库名称发生变化时,我都不想更新所有车辆。
有没有办法用ngOptions标记optgroups,还是应该在这种情况下使用ngRepeat?
答案 0 :(得分:19)
您可以在getGarageName()
中拨打group by
,而无需使用as
...
ng-options="car.id as car.name + ' (' + car.color + ')' group by getGarageName(car.garageId) for car in cars"
您可能需要考虑在车库阵列中存储对车库对象的引用,而不是将车库ID存储在每辆车中。这样你可以改变车库名称,而不需要更换每辆车。而group by
只会变成......
group by car.garage.name