Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 908
Fabio Nolasco Avatar asked Dec 05 '22 10:12

Fabio Nolasco


2 Answers

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

like image 64
Dan Avatar answered Dec 06 '22 23:12

Dan


You could first get the current year as a Javascript date object, then use a for loop to find the next nineteen sequential years. Then, pass these as an array to the view.

Controller:

var year = new Date().getFullYear();
var range = [];
range.push(year);
for(var i=1;i<20;i++) {
  range.push(year + i);
}
$scope.years = range;

View:

<select ng-options="year for year in years">
</select>

and if I understand you correctly, a similar approach to make a months dropdown controller:

var range = [];
for(var i=1;i<13;i++) {
  range.push(i);
}
$scope.months = range;
like image 26
Jakemmarsh Avatar answered Dec 06 '22 23:12

Jakemmarsh