Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Create Dynamic year dropdown

I want to create a year selection dropdown. year must start from this year upto next 7 years .

I have tried

var year = new Date().getFullYear();
var range = [];

range.push(year);

for (var i = 1; i < 7; i++) {
    range.push(year + i);
}

$scope.years = range;

<select class="form-control"  ng-options="year for year in years" name="expiryMonth" ng-model="expiryMonth" required>'

But this creates a html ,

<option label="2016" value="number:2016">2016</option>

this creates a required year dropdown But i want Value to be last two digits of label

Also, my first option should be like

<option value="">select month</option>
like image 343
monda Avatar asked Dec 05 '25 19:12

monda


2 Answers

angular.module('app', [])
    .controller("Ctrl",
    function contactListCtrl($scope) {

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


    });
<!DOCTYPE html>
<html ng-app="app">

<head>
    <link data-require="[email protected]" data-semver="3.3.6" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" />
    <script data-require="[email protected]" data-semver="1.4.9" src="https://code.angularjs.org/1.4.12/angular.js"></script>

    <script src="script.js"></script>
</head>

<body ng-controller="Ctrl">

<select class="form-control" ng-model="expiryMonth" required>
  <option>Select month</option>
  <option ng-repeat="year in years">{{year}}</option>
  </select>
</body>

</html>
like image 169
Stark Buttowski Avatar answered Dec 08 '25 07:12

Stark Buttowski


This will give you a useful dynamic year range.

let years: number[] = [];
let currentYear: number = new Date().getFullYear();
for(let i = (currentYear - 7); i < (currentYear + 7); i++) {
    years.push(i);
}
like image 38
Francois Stander Avatar answered Dec 08 '25 07:12

Francois Stander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!