-1

I want to print 2014-2050 in angular js. I have tried to find it in google and SO and i got below

<select class="form-control" >
<option  ng-repeat="n in [2014,2015,2016, .. 2050]" value="{{n}}">
    {{n}}
</option>                               
</select> 

I am currently learning angular js. I want to run a loop between a defined range? like in php if i want to run a loop between 2014-2050 the i will do this

for($i=2014;$i<=2050;$i++)
{
  echo $i;
}

How can i run the above for loop in angular js. Please help me.

Bik
  • 553
  • 10
  • 31

4 Answers4

2

You have to create range in your controllers and use either ng-repeat or ng-options. ng-options is better.

JS

angular.module('app', [])
.controller('MyController', function($scope) {
    var years = [];
    for (var i = 2014; i <= 2050; i++) {
       years.push(i);
    }
    $scope.years = years;
});

HTML

<select class="form-control" >
    <option  ng-repeat="year in years" value="{{year}}">
        {{n}}
    </option>
</select> 

(or) You can use ng-options

<select ng-model="selectedYear" ng-options="year for year in years"></select>
Fizer Khan
  • 88,237
  • 28
  • 143
  • 153
1

It's probably best to initialise the array of dates in the controller (or even better, in a service), and then loop over the pre-created array in the template. So in the controller:

$scope.dates = [];

var initDates = function() {
  var i;
  for (i = 2014;i <= 2050; i++) {
    $scope.dates.push(i);
  }
}

initDates();

And then in the template:

ng-repeat="date in dates"

Which can be seen at http://plnkr.co/edit/9K9VhAAM9HxopDlCVLi9?p=preview

Michal Charemza
  • 25,940
  • 14
  • 98
  • 165
0

Its not mentioned in the angular docs, but you can use the limitTo filter twice to slice a range in a array/object.

https://docs.angularjs.org/api/ng/filter/limitTo

Its as simple as this:

<li ng-repeat="item in items | limitTo:10 | limitTo:-5">{{item}}</li>

working demo: http://plnkr.co/edit/8LXXnH?p=preview

cheekybastard
  • 5,535
  • 3
  • 22
  • 26
0

use the custom Filters here.

<div ng-app='myApp' ng-controller="Main">
    <li ng-repeat="date in [] | range:2050">{{date}}</li>
</div>

var myApp = angular.module('myApp', []);
myApp.filter('range', function() {
  return function(input, total) {
    total = parseInt(total);
    for (var i=2014; i<=total; i++)
      input.push(i);
    return input;
  };
});
chandu
  • 2,276
  • 3
  • 20
  • 35