Why dropdown selecting last value

删除回忆录丶 提交于 2019-12-08 00:37:15

问题


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')

      }
})

回答1:


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.




回答2:


Angular's ng-model keeps in sync value of the target property and state of the widget. In your case it means that option with CountryID equal to your controller's scope CountryID is selected. I do not see any definition of controller's CountryID, so I think you should try to be explicit.

Set up your empty option as

<option value="-1">Select Country</option>

And add CountryID initialization in controller

$scope.CountryID = -1;


来源:https://stackoverflow.com/questions/41489965/why-dropdown-selecting-last-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!