angularjshtml-selectng-options

Angular ng-options for bounded select elements


I'm almost there but stuck on one little detail. I can't seem to get the "name" property of the selected Car Make's "Car Model" to actually show up on the select menu. At the moment, it seems to be showing the correct number of options, but the options are visibly BLANK. Here's my code to help better explain...

$scope.carMakes = [
    {
        name: 'Honda',
        models: [{name:'Accord'}, {name: 'Civic'}, {name: 'CRX'}]
    },
    {
        name: 'Toyota',
        models: [{name:'Camry'}, {name: 'Forerunner'}]
    }
];

   <div class="input-group">
        <label>Vehicle Make</label>
        <select id="carMake" ng-model="carMake" ng-options="carMake as carMake.name for carMake in carMakes track by carMake.name">
            <option value="">All</option>
        </select>
    </div>
    <div class="input-group carModels">
        <label>Vehicle Model</label>
        <select id="carModel" ng-model="carMake.model" ng-options="carMake.model as carMake.model.name for carMake in carMake.models">
            <option value="">All</option>
        </select>
   </div>

Can someone please tell me why even though the carModel select options show up, the "name" isn't being displayed? Thank you!


Solution

  • You want something like this:

    <select id="carModel" ng-model="carMake.model" ng-options="carModel as carModel.name for carModel in carMake.models">
        <option value="">All</option>
    </select>
    

    We're using carModel.name as the display and setting the value as the object itself. So in your controller, $scope.carMake.model will be equal to the model object. So if the user selects "Accord" then in your controller:

    $scope.carMake.model.name === 'Accord' // True
    

    would evaluate to true after the selection is made.