Alan2
Alan2

Reputation: 24572

Can I use ng-repeat to iterate over an array in AngularJS?

I am having some trouble with using AngularJS ng-repeat. Here is what I have:

<div ng:show="selected == 3">
    <div class="columns">
        <textarea rows="4" data-ng-model="modal.data.answer[1].text" cols="91">1</textarea>
    </div>
    <div class="columns">
        <label>Explanation</label>
        <textarea rows="2" data-ng-model="modal.data.answer[1].explanation" cols="91"></textarea>
    </div>
    <div class="columns">
        <div class="colx2-left">
            <span class="label">Correct</span>
            <input type="checkbox" data-ng-model="modal.data.answer[1].correct" class="check-box"><input type="hidden" value="false" name="Details[0].Correct">
        </div>
        <div class="colx2-right">
            <label>Image File</label>
            <input type="text" data-ng-model="modal.data.answer[1]image" class="full-width">
        </div>
    </div>
</div>

The modal.data.answer array will always have six elements. Can I use ng-repeat to create the HTML for these and have it repeat even the [x] numbers in the array and have it increment the number on the first line for "selected =" from 3 to 8 ?

As far as I know I can use <div ng-repeat="t in [3,4,5,6,7,8]"> </div> but how can I get the values of t into things like:

data-ng-model="modal.data.answer[1].text"

Upvotes: 26

Views: 68515

Answers (2)

Eassa Nassar
Eassa Nassar

Reputation: 1230

Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys.

  <div ng-repeat="n in [42, 42, 43, 43] track by $index">
     {{n}}
  </div>

Upvotes: 19

DotDotDot
DotDotDot

Reputation: 3566

your edit is heading in the right way, you can iterate through a list of integers easily, the you just use the value of you index like that

<div ng-repeat="t in [3,4,5,6,7,8]">
....
data-ng-model="modal.data.answer[t].text"
...

I made a fiddle if you want to try http://jsfiddle.net/DotDotDot/tweyS/ (the input field is just here to change the selected value, as in your code sample, in order to display the right fields)

have fun

Upvotes: 26

Related Questions