Search code examples
angularjsangularjs-ng-repeatangularjs-select

Default selected value in select with ng-repeat


I'm trying to have a default selected value with ng-selected but it doesn't works.

My code is

<select 
    id="department" 
    name="department" 
    class="form-control"
    ng-model="editProfilCtrl.infos.department"
    ng-change="editProfilCtrl.findCities()">
        <option 
            ng-repeat="dep in editProfilCtrl.infos.departments" 
            class="text-uppercase" 
            value="{{dep}}"
            ng-selected="{{dep.idDepartment == editProfilCtrl.infos.department}}">
            {{editProfilCtrl.infos.department}} - {{dep.idDepartment}} - {{dep.code}} - {{dep.name}}
        </option>
</select>

In my dropdown list I have this results :

  • (empty)
  • 1 - 1 - Code01 - TEST1
  • 1 - 2 - Code02 - TEST2
  • 1 - 3 - Code03 - TEST3
  • ...

You can see that editProfilCtrl.infos.department = 1. So, normally it must be selected by default. But this is the empty line which is selected :/. Do you have an idea ?

Thanks.

Edit : the mac gyver "solution" :

<select 
    id="department" 
    name="department" 
    class="form-control"
    ng-model='editProfilCtrl.infos.department' 
    ng-change="editProfilCtrl.findCities()"
    ng-options='dep as dep.code + " - " + dep.name for dep in editProfilCtrl.infos.departments'>
</select>

with in my controller :

self.infos.selectedDepartment = editProfilFormDto.department;
self.infos.departments = editProfilFormDto.departments;
self.infos.department = self.infos.departments[self.infos.selectedDepartment - 1];

Solution

  • have you checked the documentation or searched on the google? based on what I know, you can't do a default value using that approach. and also there is a dedicated directive for making options efficiently.

    I'm a newbie but hope I helped you with my answer.

    use ngOptions https://docs.angularjs.org/api/ng/directive/ngOptions

    /** 
      somewhere in your controller
    */
        editProfilCtrl.infos.department = editProfilCtrl.infos.departments[0]
      <select 
        id="department" 
        name="department" 
        class="form-control"
        ng-model="editProfilCtrl.infos.department"
        ng-change="editProfilCtrl.findCities()" ng-options="dep.idDepartment+' '+dep.code+' '+dep.name for dep in editProfilCtrl.infos.departments"></select>