简体   繁体   中英

set selected value of drop down list in angularjs

HTML code

<div>
            <label for="name">School Name</label>
            <select ng-model="SelectedSchoolIDEdit"
                    ng-options="option.Name for option in SchoolAvailableOptions track by option.ID"></select>
        </div>

Angular code

 SchoolGradesService.GetAllSchools().then(function (d) {
    $scope.SchoolAvailableOptions = d.data;// Success
    $scope.SelectedSchoolIDEdit = $scope.SchoolAvailableOptions[0].ID;
}, function () {
    alert('Error Occured !!!'); // Failed
});

The situation like that i get data successfully and i can fill the drop down list but The problem is that I cant set the default value on it And I search a lot and i see the same what I do ,SO I cannot catch the problem Note: I am new with Angular

Replace $scope.SelectedSchoolIDEdit = $scope.SchoolAvailableOptions[0].ID;
by $scope.SelectedSchoolIDEdit = $scope.SchoolAvailableOptions[0];

Check the documentation

Here's a JSFiddle

try this

<select ng-init="SelectedSchoolIDEdit=SchoolAvailableOptions[0].ID" ng-model="SelectedSchoolIDEdit"
                ng-options="option.ID as option.Name for option in SchoolAvailableOptions track by option.ID"></select>

Here is my solution for my problem. I did a data mockup of your data. I was able to select the option, when the scope variable $scope.SelectedSchoolIDEdit will need to have the syntax to be.

$scope.SelectedSchoolIDEdit = {ID: 1};

So to solve your problem, the code that uses the service should be like this.

SchoolGradesService.GetAllSchools().then(function (d) {
    $scope.SchoolAvailableOptions = d.data;// Success
    $scope.SelectedSchoolIDEdit = {ID: $scope.SchoolAvailableOptions[0].ID};
}, function () {
    alert('Error Occured !!!'); // Failed
});

Here is a working example of how the data should be for the options to be selected.

Can you please check if this change fixes your issue?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM