Angular.js Select with ngOptions: Label the optgroup
Asked Answered
S

1

10

I just started to play with Angular.js and have a question about ngOptions: Is it possible to label the optgroup?

Lets assume 2 objects - cars and garages.

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"},
    ...
]

With this code I got nearly the result I want:

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

Result in the select:

-----------------
1
 Diablo (red)
 Countach (white)
 Firebird (red)
2
 Clio (silver)
 Golf (black)
3
 Hummer (silver)
-----------------

But I want to label the optgroups like "Garage 1", "Garage 2", ... or even better display the name of the garage and not just the garageId.

The angularjs.org documentation for select says nothing about labels for the optgroup, but I would like to extend the group by part of ngOptions like group by car.garageId as 'Garage ' + car.garageId or group by car.garageId as getGarageName(car.garageId) - which sadly is not working.

My only solution so far is to add a new property "garageDisplayName" to the car objects and store there the id + garage name and use that as group by parameter. But I don't want to update all cars whenever a garage name is changed.

Is there a way to label the optgroups with ngOptions, or should I use ngRepeat in that case?

Scutari answered 12/4, 2014 at 21:10 Comment(0)
C
21

You can just call getGarageName() in the group by without using an as...

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

Instead of storing the garage id in each car, you might want to consider storing a reference to the garage object in the garages array. That way you can change the garage name and there is no need to change each car. And the group by simply becomes...

group by car.garage.name

Chartist answered 12/4, 2014 at 21:44 Comment(2)
Thanks a lot! I always tried it with the as part instead of just write the expression I want to display. :) So it's also possible to do group by 'Garage ' + car.garageId.Scutari
And as you suggested I considered to store the reference of the garage instead the id and ended with this: group by car.garage.name + ' - ' + car.garage.id (garage name is not unique) which indeed is simpler.Scutari

© 2022 - 2024 — McMap. All rights reserved.