3

Basically, I have an input control element where you can enter the total number of apples you have and based on the number of apples I want to set the max number of mini-apple pies you can make (for every 1 apple you can make 1 mini-apple pie). The Angularjs documentation states to use ngOptions, but I just want to base it off a primitive (total number of apples) not a model.

So, if I have a totalApples value of 2, then I want to have 2 options generated (with one having the value of 1 and the other the value of 2)

My code so far is as follows:

HTML snippet:

<input ng-model="totalApples" />
<select ng-options="">
  <option value="1">1</option>  //what I would like to have is the options generated 
  <option value="2">2</option>
</select>

In my controller I set the scope:

 $scope.totalApples = 2;

Thank you

ollo
  • 24,797
  • 14
  • 106
  • 155
0--
  • 221
  • 1
  • 6
  • 16

2 Answers2

6

If you're interested in the selected value you should really use the ng-options directive in combination with ng-model. Take a look at this example.

Also, don't be confused with the option values you see when you inspect the option elements. Angular makes sure correct value is bound to your model.

Martin
  • 8,876
  • 2
  • 35
  • 36
  • Thanks, Martin, for your example and remarks. This is the approach I would like to use as it seems to be the most straight forward while still solving my problem in an Angularish way (though putting in a filter probably is recommended) – 0-- Apr 29 '13 at 23:01
3

You would want a custom function to handle the generation of options for you. AngularJS directives work with data, the rest is up to you. Your goal is to supply it.

In your controller

$scope.options = [];
$scope.generateOptions = function() {
  newOptions = [];
  for (var i = 1; i <= $scope.totalApples; i++) {
    newOptions.push(i);
  }
  $scope.options = newOptions;
}

And in your HTML you can simply use repeater since you don't really require select directive for this simple scenario.

<input ng-model="totalApples" />
<select>
  <option ng-repeat="option in options" value="{{option}}">{{option}}</option>
</select>
<button ng-click="generateOptions()">Generate options!</button>
Bogdan Rybak
  • 2,107
  • 1
  • 19
  • 22
  • Also here's an answer similar to yours using a filter: http://stackoverflow.com/questions/11160513/angularjs-ng-options-create-range/11161353#11161353 – petebowden Apr 29 '13 at 18:01
  • Thank you, RickCigarette, for the response and the link, Rastapopulous, using a filter. It was helpful – 0-- Apr 29 '13 at 21:32