Patrick Patrick - 1 year ago 50
AngularJS Question

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

I have the following dropdown select HTML tags

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

<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 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 ng-if="params.CarName!= 'BMW' && params.CarName != 'Audi'">

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
1: Object

Answer Source

You need an array with the Car Names, eg.

$scope.carNameOptions = [

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>

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>


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