While creating an angular form, we come upon a situation where we required to generate the sequence of years in the select HTML tag. There is some way to perform this task, but each has its limitation. Let's look the way to generate the years :
HTML Code:
- Hard code an array having years in your controller and assign it to some $scope variable.
- Use for loop to generate the years and then assign to $scope variable.
- Send $http request to generate the array of year and assign the response data to $scope variable.
- Define a filter that will be used to generate the sequence of years.
HTML Code:
<form name="myform">
<select ng-options="year for year in [] | range: '2000':'2017'" ng-model="user.year" name="year" id="year" class="form-control"></select>
</form>
Javascript Code:
app.filter('range', function() {
return function(input, start, end) {
if(start == '') {
start = (new Date()).getFullYear();
}
if(end == '') {
end = (new Date()).getFullYear();
}
start = parseInt(start);
end = parseInt(end);
var direction = (start <= end) ? 1 : -1;
end = (direction == 1) ? (end+1) : (end-1);
while (start != end) {
input.push(start);
start += direction;
}
return input;
};
});
How to use:- Generating years in ascending order:
ng-options = "year for year in [] | range: '2000':'2018'"
- Generating years in descending order:
ng-options = "year for year in [] | range: '2018':'2000'"
- Generating years from given year to current year:
ng-options = "year for year in [] | range: '2000':''"
- Generating years from current year to given year:
ng-options = "year for year in [] | range: '':'2000'"
very useful information, the post shared was very nice.
ReplyDeleteFull Stack Online Training