Reputation: 623
I am using AngularJS. I am trying to bind a dropdown with value shown from response. But I am not able to set the selected data. It always shows the default. Below is the index.cshtml:
<div class="col-sm-4">
<select name="CopyseasonTypeSelect" ng-model="CopyselectedSeasonType" ng-options="CopySeason.SeasonTypeName for CopySeason in seasons">
<option value="">-- Select the Season --</option>
</select>
</div>
In controller.js
testAPIService.getSeasonById(nId).success(function(response) {
$scope.seasonByIdReponse = response;
$scope.CopyselectedSeasonType = response.SeasonType; // I am getting "Summer"
$scope.init();
});
}
The dropdown has the values "-- Select the Season -- ", "Winter", "Summer", "Spring"
The object array is as below:
[object Object],[object Object],[object Object],[object Object]
[
0: {
[functions]: ,
$$hashKey: "object:78",
__proto__: { },
Id: 1,
ImageUrl: "testicon.png",
SeasonDetail: null,
SeasonTypeName: "Winter"
},
1: { },
2: { },
3: { },
length: 4
]
How to set the value in the dropdown from the service?
Upvotes: 0
Views: 7578
Reputation: 2542
<select name="CopyseasonTypeSelect"
ng-model="CopyselectedSeasonType"
ng-options="i.SeasonTypeName as i.SeasonTypeName for i in seasons">
<option value="" style="display: none">-- Select the Season --</option>
</select>
Upvotes: 1
Reputation: 20016
Try this. Use track by
in the ng-options
to initialize it
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
<div class="container">
<select name="CopyseasonTypeSelect" ng-model="CopyselectedSeasonType" ng-options="CopySeason.SeasonTypeName for CopySeason in seasons track by CopySeason.Id">
<option value="">-- Select the Season --</option>
</select>
</div>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope) {
$scope.seasons = [{
SeasonTypeName: "Winter",
Id: 0
},
{
SeasonTypeName: "Summer",
Id: 1
},
{
SeasonTypeName: "Spring",
Id: 2
}];
$scope.CopyselectedSeasonType = $scope.seasons[1];
});
</script>
</body>
</html>
Upvotes: 1