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

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

What about a fall with the months of the year (1..12) using an 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.

+4
source share
4 answers

This would be a good opportunity to create a directive for reuse. Here's an example for years, and the same thing could be done in a few 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 the fiddle

+14
source

You can first get the current year as a Javascript date object, and then use the for loop to find the next nineteen consecutive years. Then pass them 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 for creating a drop-down month dispatcher:

 var range = []; for(var i=1;i<13;i++) { range.push(i); } $scope.months = range; 
+3
source

I would think that something like this is pretty simple.

Controller:

 $scope.years = [2013, 2014, 2015...] 

View:

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

This will be your viewing part.

 <select ng-options="month as month.title for month in proficiencyMatrixCtrl.months track by month.id" ng-model="<your controller_name>.currentMonth" ng-change="<your_controller>.<your_controller_inside_function()"> </select> 

You need to get the value in the controller function using the syntax below:

 console.log($scope.currentCurrent); 
-1
source

Source: https://habr.com/ru/post/1485684/


All Articles