3

I have an array of objects and when i go to populate the select with the elements, it doesn't pre-select the currently active one. If i change the select it all works as intended, but the pre-selected element is not selected on page load.

JS:

$scope.license_year_list = [
    {label:"Year of 1991", value:1991}, 
    {label:"Year of 1992", value:1992}  ];

$scope.item = {license_year: {label:"Year of 1992", value:1992}};

HTML:

<div ng-controller="MyCtrl">
    <select ng-model="item.license_year" 
            ng-options="y.label for y in license_year_list">
    </select>
</div>

Fiddle: http://jsfiddle.net/eXvH8/

1

2 Answers 2

2

Angular checks for equality based on reference of the actual object/value. To make your select box start out with the default value, do a simple assignment of the default value. Change your code like this:

HTML:

<div ng-controller="MyCtrl">
<select ng-model="item" ng-options="y.label for y in license_year_list"></select>

<br/><br/><br/>
{{item.license_year}}
</div>

JS:

function MyCtrl($scope) {
$scope.license_year_list = [{label:"Year of 1991", value:1991}, {label:"Year of 1992", value:1992}];

$scope.item = $scope.license_year_list[1];
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks ~ The $scope.item definition is a little wrong, it still needs to be an object where the license_year is your value.
1

The equality of the objects are evaluated by reference, so you need use the exactly same object when you want to select it.

$scope.item = {
    license_year: $scope.license_year_list[1]
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.