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.
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
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With