Search code examples
javascripthtmlangularjsangularjs-directiveng-options

What is the best way to create drop downs with numbers representing the next 20 years using nd-repeat on AngularJS?


What is the best way to create drop downs with numbers representing the next 20 years using ng-repeat on AngularJS? It would be good to get the first year (the current year) dynamically.

And what about a drop down with the months of the year (1..12) using the iterator?

NOTE: I found a good idea here: http://www.zzzxo.com/q/answers-angularjs-for-loop-with-numbers-ranges-11873570.html

However, I wonder if there is a shorter way.


Solution

  • This would be a good opportunity to create a directive for reusability. Here is an example for years, and the same type of thing could be done for months. Use ng-options instead of ng-repeat.

    HTML:

    <div year-drop offset="0" range="20"></div>
    

    Directive:

    angular.module('myapp',[]).directive('yearDrop',function(){
        function getYears(offset, range){
            var currentYear = new Date().getFullYear();
            var years = [];
            for (var i = 0; i < range + 1; i++){
                years.push(currentYear + offset + i);
            }
            return years;
        }
        return {
            link: function(scope,element,attrs){
                scope.years = getYears(+attrs.offset, +attrs.range);
                scope.selected = scope.years[0];
            },
            template: '<select ng-model="selected" ng-options="y for y in years"></select>'
        }
    });
    

    Here is a fiddle