Search code examples
angularjsangular-ngmodelng-options

Why dropdown selecting last value


Here i try to Loading data into dropdownList Its Loading But why By default it select last value from the List.

Html

<div ng-controller="Part5Controller">
    Country : <select ng-model="CountryID" ng-options="I.CountryID as I.CountryName for I in CountryList" ng-change="GetState()">
        <option value="">Select Country</option>
    </select>
</div>

controller.Js

app.controller('Part5Controller', function ($scope, servicemard) {
    getCountrys();
    function getCountrys() {
        var xx = servicemard.getctrys();
        xx.then(function (d) {
            $scope.CountryList = d.data;
        })
    }
})

service.js

app.service('servicemard', function ($http) {
    this.getctrys = function () {
        return $http.get('/Jan/GetCountries')

      }
})

Solution

  • You might want to kill two birds with one stone. Giving the "prompt" option a value makes you then have to deal with it. Probably the better way is to pre select and disable it.

    <div ng-controller="Part5Controller">
        Country : <select ng-model="CountryID" ng-options="I.CountryID as I.CountryName for I in CountryList" ng-change="GetState()">
            <option value="" selected disabled>Select Country</option>
        </select>
    </div>
    

    Now, the prompt is selected by default but cannot be actually selected for the binding. My experience is with a null value on the binding without a selection results in the last item in the list being selected by default.