Patrick Patrick - 4 months ago 13
AngularJS Question

get dropdown value for SELECT from db instead of hardcoding at UI (Angularjs)

I have the following dropdown select HTML tags

<label>Car:</label>
<select ng-model="params.CarName">
<option value="x" disabled="" selected="">Select Car...</option>
<option value="BMW">BMW</option>
<option value="Audi">Audi</option>
</select>

<label>Model:</label>
<select ng-if="params.CarName == 'BMW'" ng-model="params.CarModel" ng-change="PerfRpt()">
<option value="x" disabled="" selected="">BMW Sports</option>
<option value="BMW 328i">BMW 328i</option>
<option value="BMW Sports">BMW Sports</option>
</select>

<select ng-if="params.CarName == 'Audi'" ng-model="params.CarModel" ng-change="PerfRpt()">
<option value=" " disabled="" selected="">Audi Sports</option>
<option value="Audi i345">Audi i345</option>
<option value="Audi Sports">Audi Sports</option>
</select>

<select ng-if="params.CarName!= 'BMW' && params.CarName != 'Audi'">
<option>-</option>
</select>


As per the above code, this is wat it does, We have a dropdown to select Car. It is either BMW or Audi.

Depending on this selection, The Model dropdown will be shown. For e.g If we select Audi for Car in the first dropdown, then Audi i345 and Audi Sports will be shown as the dropdown in the 'Model' field.

Similarly, other options will be shown if we select BMW.

Now I am planning to put the Car data in DB along with Model data. Once the page loads, the data will be retrieved and displayed to the user for the 'Car' section. Once the car is selected, depending on the value of the car, its corresponding Model will be updated in the Model section then.

I can get the data from backend to frontend. I want to know how to display those values dynamically and not hardcode like I have done here.

I have the following response from database for the Car.

Results: Array[2]
0: Object
Car:BMW
1: Object
Car:Audi

Answer

You need an array with the Car Names, eg.

$scope.carNameOptions = [
    'BMW'
    'Audi'
];

Then you would do this:

<select ng-model="params.CarName">
    <option value="">Select car...</option>
    <option ng-repeat="car in carNameOptions" value="{{car}}">{{car}}</option>
</select>

I would suggest making params.CarModel an object with the keys being the CarNames, and the value an array with options for the car like above. Then you can do this:

<select ng-model="params.CarModel">
    <option value="">Select model...</option>
    <option ng-repeat="carModel in carModelOptions[params.CarName]" value="{{carModel}}">{{carModel}}</option>
</select>

eg

$scope.carModelOptions = {
    'BMW' : [
        'BMW 328i',
        ...
    ],
    'Audi' : [...]
}
Comments