问题
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