0
<label>Number of Meals :
 <input type="number" name="meals" min="0" class="input" ng-model="meals"><br>
</label>

What I want to do is use the number entered by the user to have 'x' number of Meal text fields which will be displayed like this.

For example, if the user entered 2:

Meal 1:
   Calories [TEXT BOX]
Meal 2:
   Calories [TEXT BOX]

I'm not too sure how I can use the number entered and create that number of Meals

halapgos1
  • 1,130
  • 4
  • 16
  • 34

3 Answers3

0

Use ng-repeat

<label ng-repeat="value in meals">Meal: {{value}}:<br>
    Calories:<input type="text">
</label>

Where meals is the scoped variable meals assigned by your input. This is essentially saying:

for(var i = 0; i < meals; i ++){
    // generate html based on the value of i
}

And if meals was an array use meals.length and then value would be equivalent to saying

value = meals[i];
user3727843
  • 574
  • 1
  • 4
  • 13
0

You would need to use ng-repeat to show n number of text boxes based on the number that the user has typed in. To do this you can use the following:

  <label ng-repeat="n in [] | range: meals">
    Meal {{ $index+1 }}:
    <input type="text" ng-model="meal[$index]" /><br/>
  </label>

This uses a custom filter that I've taken from this answer. Here is a plnkr showing this working.

Community
  • 1
  • 1
keithm
  • 938
  • 6
  • 9
0

You can achieve this by using a filter.

Javascript:

var app = angular.module('app', []);

app.filter('range', function() {
  return function(input, total) {
    total = parseInt(total);

    for (var i=0; i<total; i++) {
      input.push(i+1);
    }

    return input;
  };
});

function Ctrl($scope){

}  

HTML

<div ng-app='app' ng-controller="Ctrl">
    Enter the meals: <input type="text" ng-model="meals" />

    <label ng-repeat="meal in [] | range:meals"><br>
        Meal: {{meal}}: <span>Calories:<input type="text"></span>
    </label>

</div>

You can read about ng-repeat. You can use ng-repeat directive to loop through array or object.

Use css rule to style the <span> if you need to display in differnet line:

label span {
   display: block;
}

Here is the working js-fiddle

Subash
  • 7,098
  • 7
  • 44
  • 70
  • Just a quick questions, for the calories input, where exactly is the calories input being stored by the "meal[$index]"? From my understanding of the controller, it seems like meals is an array of objects which has 2 attributes (number and calories). I'm just a little confused how we are setting each Calories input to the calorie attribute. – halapgos1 Aug 18 '15 at 19:42
  • @halapgos1 I have updated my answer to simplify the solution and hopefully easier for you to understand. I now uses filters. jsfiddle is updated too. – Subash Aug 18 '15 at 23:26