Mark
Mark

Reputation: 3207

dynamically change ng-options

I currently have the following select input

<select
    ng-model="people"
    ng-options="capacity for capacity in Range(1, roomCapacity)"
    class="form-control"
    id="howmany"
    ng-required="noOfPeopleRequired()">
</select>

range is

$scope.Range = function(start, end) {
    var result = [];
    if (end === 1) {
        result.push(1);
    } else {
        for (var i = start; i <= end; i++) {
            result.push(i);
        }
    }
    return result;
};

I am watching an int and when that changes setting the value of roomCapacity to it but unfortunately the range of options does not change in my select

How should I be doing this?

Upvotes: 0

Views: 719

Answers (1)

Chickenrice
Chickenrice

Reputation: 5727

Fo array data source, you could use the expression below:

select as label for value in array

Try this:

JS

.controller("myCtrl",function($scope){
    $scope.Range = function(start,end){
        var result = [];
        if(end===1){
            result.push(1);
        }else{
            for(var i=start;i<=end;i++){
                result.push(i);
            }
        }
        return result;
    }
});

HTML

<div ng-controller="myCtrl">
  <input type="text" id="roomCapacity" ng-model="roomCapacity"/>
  <select
    ng-model="people" ng-options="capacity as capacity for capacity in Range(1,roomCapacity)"
  >
    <option value="">Please select</option>
  </select>
</div>

Here is a jsFiddle DEMO

Upvotes: 2

Related Questions