Question

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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top