user1532669
user1532669

Reputation: 2378

Selecting default option from angular select list

I need to select the following month from a select list. I can get the correct value but can't select the option from the list.

Can anyone see what I'm doing wrong here? I tried a few things from this related question but didn't get anywhere.

This is object that I'm trying to use as the default selected option:

Object { title="November", value="11", sortOrder=11}

Here is my html:

<div class="search-box__select half">
    <select data-ng-model="search.Month" data-ng-disabled="!months" data-ng-options="month.value as month.title for month in months">
        <option value="">-- Select Month --</option>
    </select>
    {{selectedOption}}
</div>

here is my angularjs code:

$scope.getMonths = function(){
    var year = $scope.search.Year;
    if(year)
    {
        $http({
        method:'GET',
        url:'/autocomplete/generatesearchmonths',
        params: { year: year }
    }).success(function(data, status, headers, config){
        $scope.months = data;
        var d = new Date();
        var n = d.getMonth();
        $scope.selectedOption = $scope.months[n].value;
        console.log($scope.selectedOption)
    }).error(function(data, status, headers, config){
        $scope.message='Error loading months'
    })
  }else{
         $scope.months = null;
  }
}

Upvotes: 1

Views: 286

Answers (2)

Mathew Berg
Mathew Berg

Reputation: 28750

Two options, you can either do what Michael Zucchetta suggested or modify your ng-options:

<select data-ng-model="search.Month" data-ng-disabled="!months" data-ng-options="month.value for month.value as month.title for month in months">
    <option value="">-- Select Month --</option>
</select>

Upvotes: 1

Michael
Michael

Reputation: 3326

You should do the following in the success callback:

$scope.months = data;
$scope.search.Month = $scope.months[0] (or whatever default option should be)

Upvotes: 1

Related Questions