1

Is there a more elegant way to do this?

<input type="text" id="items" ng-model="items[0]" placeholder="item1">
<input type="text" id="items" ng-model="items[1]" placeholder="item2">
<input type="text" id="items" ng-model="items[2]" placeholder="item3">
<input type="text" id="items" ng-model="items[3]" placeholder="item4">
<input type="text" id="items" ng-model="items[4]" placeholder="item5">

I want to use ng-repeat but there are no items to iterate through because items is empty at first.

3
  • Why do you want to see them if they are empty? Maybe a little more context would be good. Commented Jul 30, 2015 at 13:47
  • 2
    You should initialize items[] in your controller or directive. Then you can ng-repeat over it. Commented Jul 30, 2015 at 13:47
  • you can create an array with 5 positions, but you need to put track by $index to allow the repeat to work Commented Jul 31, 2015 at 12:20

4 Answers 4

6

ng-repeat won't iterate on an empty array. You could try settings items to an array of 5 empty objects, then update the objects later.

Sign up to request clarification or add additional context in comments.

Comments

3

You may want to set items in the controller like the following:

$scope.items = [null, null, null, null, null];

With this you will have an array to iterate over.

Comments

2

You can use track by $index to list a null-filled array:

see in jsbin

<div ng-repeat="item in c.list track by $index">
    <input type="text" id="items" ng-model="c.list[$index]" placeholder="item{{$index + 1}}">
</div>

Comments

0

Or you could actually initialize it differently in your controller, with the new keyword.

  $scope.items = new Array(5);

Comments

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.