Search code examples
javascripthtmlangularjsdrop-down-menuangularjs-select

Dynamically change dropdown select defaults depending on existing values in array


I am new to web development and AngularJS and I have been struggling with how to go about this. Sorry for the bad English.

I use an ng-repeat that creates the correct number of dropdowns I need as this needs to be dynamic. The dropdowns have a label like:

Test1: <dropdown here>
Test2: <dropdown here> ...etc.

I have a HTTP request that returns an array. If the array has "Test1 State1" in it, I would like the dropdown for Test1: to change to State1 on default. (continues with all the Tests)

How can I go about this?

HTML

<div ng-repeat="o in options track by $index">
    <label for="{{::$o}}" class="col-xs-3">{{o}}:</label>
    <select id="{{::$o}}" ng-model="stateModel"
            ng-options="state.changeToState for state in states"
            ng-change="onStateSelect(stateModel.platformReleaseNotes, o)"> 
      {{state}}
    </select>
</div>
$scope.states = [
    {
      changeToState: 'State1',
      notes: 'Hello World'
    },
    {
      changeToState: 'State2',
      notes: 'Goodbye'
    },
    {
      changeToState: 'State3',
      notes: ' is State3'
    },
    {
      changeToState: 'State4',
      notes: ' is State4'
    }
  ];

Solution

  • You cannot share model if you want to have different values for all drop downs. ng-model should be different for all drop downs and this can be achieved by having array of drop downs as below.

      $scope.dropDowns = [{
        dropDownName: 'Test1:',
        id: 'test1',
        selectedOption: ''
      }, {
        dropDownName: 'Test2:',
        id: 'test2',
        selectedOption: ''
      }];
    

    see the running example in http://plnkr.co/edit/jsAn1jwGkQfxXK5I9G6J?p=preview