Reputation: 425
I'm displaying years in adropdown list by using a custom directive.This is the template for directive.
template: '<select class="form-control" ng-model="joining.Year" ng-options="year for year in Years"></select>'
Html is like that
<div years-dropdown range="50"></div>
Years is an array of strings.Year field is of string type on my server side model.Selected value is stored correctly in the database but when I reload the page(fetch the model from the database) I get the correct value in my controller but value is not displayed as selected in the dropdownlist.
Edit One thing more when I change the selection of dropdownlist and check the html it still shows the default value as selected(first option has selected attribute). However my scope object is updated correctly.
Upvotes: 0
Views: 502
Reputation: 5537
The problem is that $scope.joining.Year
and Years[$index]
is not the same object reference. I don't believe ngOptions
directive uses equivalence logic. So this is the fix to do it manually (put this into your .then()
function:
for(var i = 0; i < $scope.Years.length; ++i) {
if(angular.equals($scope.Years[i], $scope.joining.Year) {
//the fix to get years[i] if it's equal to joining.Year
$scope.Years[i] = $scope.joining.Year;
}
}
//finally, apply data into joining
angular.extend($scope.joining, data);
Upvotes: 1