3

I'm having trouble preselecting an option in an select2 select box using Angular and an ng-model. Here's my code:

Angular code in controller

$scope.filter = {
  searchValue: '',
  departmentId: 'Department2'
}

HTML

<select 
    class="form-control"
    ui-select2="{allowClear: true}" 
    ng-model="filter.departmentId">
    <option value=""></option>
    <option ng-repeat="(department, majors) in departments" value="{{department}}">{{department}}</option>
</select>

Data

{
  "Department1": [
   {
      "Name": "Major1",
      "Id": 1
   },
   {
      "Name": "Major2",
       "Id": 2
   },
   {
      "Name": "Major3",
      "Id": 3
   }
  ],
  "Department2": [
   {
      "Name": "Major4",
      "Id": 4
   },
   {
      "Name": "Major5",
      "Id": 5
   },
  ]
}

As far as I can tell, this works in version 0.0.2 of angular-ui-select2 but not above that version. I can't find any information on how to do this.

Thanks in advance!

Bjarki
  • 221
  • 1
  • 4
  • 11

1 Answers1

0

You are assigning a string value to "$scope.filter.departmentId" where as the values of generated after rendering by browser is string which is internally mapped to object. So direct assignment will not work here. The design looks smelly here. Either you make a separate array of strings or you could give an id to select tag and fetch the element using javascript and then assign a value to it.

Abhishek Jha
  • 935
  • 2
  • 10
  • 22