Panda4Man
Panda4Man

Reputation: 585

Using input value in ng-repeat

I'm having some trouble getting this to work. I have a form inside of a modal and I would like to generate some inputs based on a number the user enters in an input just above.

<form ng-submit="saveNewCategory(cat)">
      <div class="list">
        <label class="item item-input">
        <span class="input-label"><strong>Name:</strong></span>
          <input type="text" value="" placeholder="Hw" ng-model="cat.title">
        </label>
         <label class="item item-input">
        <span class="input-label"><strong>Number of {{cat.title}}</strong></span>
          <input type="tel" value="" ng-model="cat.number">
        </label>
        <!-- PROBLEM IS HERE -->
        <label class="item item-input" ng-repeat="i in range(cat.number)">
        <span class="input-label"><strong>blah</strong></span>
        <input type="tel" value="" >
        </label>
        <label class="item item-input">
        <span class="input-label"><strong>Total Points:</strong></span>
          <input type="tel" value="" ng-model="cat.total">
        </label>
        <label class="item item-input">
        <span class="input-label"><strong>Weight:</strong></span>
          <input type="tel" value="" ng-model="cat.weight">
        </label>
      </div>
      <div class="padding">
        <button type="submit" class="button button-block button-positive">Save</button>
      </div>
    </form>

In my controller that range function is

$scope.range = function(n) {
    return new Array(n);
};

So why is this not working? Only one input element ever gets generated. Can you not use form model object values in ng-repeat?

Thanks for any and all help!

Upvotes: 0

Views: 626

Answers (1)

scarlz
scarlz

Reputation: 2512

Currently, your $scope.range function is creating a new array with a string representation of val, which means it'll only ever have one element (the value itself). Instead, try:

$scope.range = function(n) {
  return new Array(Number(n));
}

Then, as you will have an array of undefined elements, you will need to use the track by option:

<label ng-repeat="i in range(cat.number) track by $index">

Or, alternatively, keep your existing markup but change $scope.range to create an array of incrementing numbers:

$scope.range = function(n) {
   return Array.apply(null, {length: n}).map(Number.call, Number);
}

Upvotes: 1

Related Questions