Search code examples
javascriptangularjsangular-ngmodel

In AngularyJs, why is my ng-model value not setting the selected option?


I have a select with 4 options. The value is set on ng-init and can only be changed by the user from that point. All my initial functions accept the value set by the ng-init and change the value works but the selected value isn't showing.

<select name="resultShow" class="result-show" ng-init="resultShow=25" ng-change="updateProd(resultShow,prodState,prodType,prodStyle,prodBrand,keywords)" ng-model="resultShow">
    <option value="25">25</option>
    <option value="50">50</option>
    <option value="75">75</option>
    <option value="100">100</option>
</select>

Solution

  • This is because select will add a default option if the model's viewValue doesn't match with one of the values present in options of select.

    viewValue of resultShow = 25 is 25 with number data type.

    At present select can bind to values of data type string. Thus there is a mismatch. In order to make it work we need to make viewValue of resultShow as 25 with string data type

    ng-init ="resultShow = '25'"
    

    will populate the select dropdown. But the datatype will be changed.

    As a workaround, please try $scope.resultShow = 25 in your controller. That will solve the problem.

    Additionally, select will automatically remove the added empty option once the viewValue is resolved.