Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS Select Box Pre-select when array is an object

Tags:

angularjs

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/

like image 452
Michael Lynch Avatar asked Dec 02 '25 03:12

Michael Lynch


1 Answers

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];
}
like image 128
John Woodruff Avatar answered Dec 05 '25 03:12

John Woodruff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!