2

I want to use ng-repeat for two different item at the same time. I mean, ng-repeat="mylist1 in list1 && mylist2 in list2"

I need to use repeat for list1 and list2.

How can i use ng-repeat for more than one item?

4
  • 2
    Assuming they're both the same length, you could always access the corresponding mylist2 item via mylist2[$index] Commented May 20, 2015 at 5:46
  • Do you want them to repeat at the same time or do you want them to join together and repeat as one variable? what i mean is do you want ng-repeat="mylist1 in list1 && mylist2 in list2" or ng-repeat="mylist in list1 and list2"? Commented May 20, 2015 at 5:48
  • how can i use $index?can you explain more? Commented May 20, 2015 at 5:49
  • i want to repeat at the same time Commented May 20, 2015 at 5:49

4 Answers 4

1

I think you'd be better off creating a combined list. For example (in your controller)

$scope.lists = list1.map(function(item, i) {
    return {
        item1: item,
        item2: list2[i] || null
    };
});

Then you can just iterate over this

<div ng-repeat="item in lists">
    <p>list1 item: {{ item.item1 }}</p>
    <p>list2 item: {{ item.item2 }}</p>
</div>

Alternatively, you could just use $index to reference the corresponding item in list2.

<div ng-repeat="item1 in list1" ng-init="item2 = list2[$index]">
Sign up to request clarification or add additional context in comments.

Comments

1

Use a function in the controller to concat them:

$scope.mergeLists = function (arr1, arr2) {
     return arr1.concat(arr2);
}

Then you have:

<div ng-repeat="mylist1 in mergeLists(list1, list2)">

Fiddle

3 Comments

Won't this just make one long list?
@Phil It will, and this solves the issue if you want to iterate over the items list by list, and not intertwined.
I get the feeling OP wants them intertwined
1

You can take advantage of ng-init

<div ng-repeat="mylist1 in list1" ng-init="i=0;lst2 = list2[i++]">

Now you can use lst2

Comments

1

I am assuming you have two lists as follows:

mylist1=[1,2,3,4,5]
mylist2=[6,7,8,9,0]

and you want to iterate over them such that the resulting elements are

[[1,6,], [2,7], [3,8], [4,9], [5,0]]

I'd suggest you take a look at zip in lodash.js (or underscore.js) - Amazing library of functions that HELP you comb and keep all your hair.

Example:
_.zip(['fred', 'barney'], [30, 40], [true, false]);
// → [['fred', 30, true], ['barney', 40, false]]

and in this case:

mergedLists = _.zip(mylist1, mylist2)
ng-repeat="item in mergedLists"

In your application js file, you can assign the result of zipping the two lists, then use ng-repeat to iterate over the values in the list. Note that each item in the list is also a list.

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.