Search code examples
javascriptangularjsangular-ngmodelng-options

AngularJS adding incremental numbers to a select list


I want a select box where I can choose from a list with a min/max number.

Currently my number is just 1 to 10 so I have the below.

<body ng-app="demoApp">
    <div ng-controller="DemoController">
            <select ng-model="selectedItem"
                ng-options="opt as opt for opt in options">
            </select>
            The value selected is {{ selectedItem }}.
    </div>
</body>
angular.module('demoApp', []).controller('DemoController', function($scope) {
  $scope.options = [1,2,3,4,5,6,7,8,9,10];
  $scope.selectedItem = $scope.options[1];
});

What is the best approach here? For example if I wanted to choose from numbers between 1 and 100 I wouldn't want to list each number just the lowest and highest. With vanilla JS I was thinking something like the below but looking for a more angular approach here so I can easily use ng-model to update my data.

var selectList = '<select>';
for (var x = 0; x < 100; x++) {
      selectList += "<option value="+ x +">" + x + "</option>";
}
selectList += '</select>';

Solution

  • angular.module('demoApp', []).controller('DemoController', function($scope) {
      $scope.options = [];
    
      //Fill array with incremental numbers
      while ($scope.options.length < 100){
        $scope.options.push($scope.options.length + 1);
      }
    
      $scope.selectedItem = $scope.options[1];
    });