Initial ng-model value not set in select

房东的猫 提交于 2019-12-03 01:26:26
sboisse

Found the problem:

The array returned by Ctrl.getAddressTypes() was an array of strings:

["0", "1", "2", "3", "1"]

and what was stored in Ctrl.type was of type number.

AngularJS compares the array supplied to ng-options to the value supplied to ng-model using the '===' operator. 3 does not equal to "3" in that case - that's why it did not work.

I often run into this when using number id's. My way around this quirk is to add ''+ to convert it to string type:

<select ng-options="''+u.id as u.name for u in users"
Pallab Bhowmik

In a function if the below code is added and the same is called from the ng-init then the issue is also getting resolved. This will resolve the string comparison issue.

$scope.Ctrl.type = "" + $scope.Ctrl.type + "";

I happens because you didn't initiated selected value. Try to set init value with ng-init:

<select ng-model="Ctrl.type" 
       ng-options="addressType for addressType in Ctrl.getAddressTypes()"
       ng-init="Ctrl.type = ..."
       ></select>

See this Demo Fiddle where we have 2 combos with and without init value. You can see that one combo HTML seems like:

<select ng-model="selectedItem1"
 ng-options="selectedItem1.name as selectedItem1.name for selectedItem1 in values" class="ng-pristine ng-valid">
   <option value="?" selected="selected"></option>
   <option value="0">General</option>
   <option value="1">Super</option>
   <option value="2">Trial</option>
 </select>

The proper one:

<select ng-model="selectedItem" 
        ng-options="selectedItem.name as selectedItem.name for selectedItem in values" 
        ng-init="selectedItem = values[1].name" class="ng-pristine ng-valid">
   <option value="0">General</option>
   <option value="1" selected="selected">Super</option>
   <option value="2">Trial</option>
</select>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!