0

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!

2

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

I wasn't able to get your first solution to work but using the map in the second solution worked. Thanks!
Re: first solution, I meant to put by $index not by $id - I've corrected my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.