0

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];
georgeawg
  • 48,608
  • 13
  • 72
  • 95
Paladice
  • 247
  • 4
  • 19

2 Answers2

2

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

A simple way can be to set editProfilCtrl.infos.department :

editProfilCtrl.infos.department = editProfilCtrl.infos.departments[0]

in your controller and don't use ng-selected

Silvinus
  • 1,445
  • 8
  • 16
  • Always not working :/ But it works with a mix of ng-options and your solutions. See my edited post ;). Thanks – Paladice Jun 14 '16 at 09:51