Search code examples
javascriptangularjsng-options

How to dynamically set default ng-options value


Situation: I need to set the default ng-options value to current year. I was able to set it using ng-init and assigning current year data from data array to the model (see the code below). Here is html:

<select
  ng-model="year_filter"
  ng-init="year_filter = year_data[3]"
  ng-change="filter_years(year_filter); closeProject(); showEditVacay = false"
  ng-options="year.name for year in year_data track by year.value"
  >
</select>

In controller,

$scope.year_data= [
    {value: '2014', name: '2014'},
    {value: '2015', name: '2015'},
    {value: '2016', name: '2016'},
    {value: '2017', name: '2017'},
    {value: '2018', name: '2018'},
    {value: '2019', name: '2019'}
]

However, I need to set the default value dynamically so that I don't have to come back next year and change the index. I tried to replace year_data[3] with new Date().getFullYear() but had no luck. Also, in the controller, I tried to generate year data dynamically but wasn't sure how to do it while keeping the first entry of the year data to 2014. Any help will be greatly appreciated!


Solution

  • If ng-model points to an object, its object reference has to equal one of the objects in the array of options. So you'd have to loop through year_data and set year_filter to the correct object:

    var year = new Date().getFullYear().toString();
    
    for (var i = 0; i < $scope.year_data.length; i++) {
        if ($scope.year_data[i].value === year) {
            $scope.year_filter = $scope.year_data[i];
    
            break;
        }
    }
    

    If you want to avoid a loop to find the correct object reference, you can have year_filter be the string year:

    $scope.year_filter = new Date().getFullYear().toString();
    

    And change ng-options:

    ng-options="year.value as year.name for year in year_data"