0

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.

4
  • When/Where/How do you set the year to scope.joining.Year? Commented Apr 27, 2016 at 20:35
  • On page load I fetch the joining object from the database and assign it to $scope.joining. joining object has a property Year .response.then(function (data) { $scope.joining= data; }) Commented Apr 27, 2016 at 20:38
  • Can you try and change the options to ng-options="year as year for year in Years" Commented Apr 27, 2016 at 20:42
  • @Alon Eitan I have tried it but did not make any difference. Commented Apr 27, 2016 at 20:45

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

KKKKKKKK I tried your answer , although it did not work but I started thinking about equality of both objects and while debugging your suggested solution it occurred to me that $scope.Years is an array of integers and my Year object is an array.It was my mistake not to give the code portion where I was populating my years array.I dont know the exact rules of marking an answer correct but your answer correctly identified the problem and lead me in the right direction.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.