2

I am using ng-repeat to generate table rows for the following object

$scope.things = [{ name: 'Bob', otherThings: [{ foo: 'hello' },{ foo: 'bye' }] },{ name: 'Sid', otherThings: [{ foo: 'cake' },{ foo: 'fish' }] }]; 

The ng-repeat expression I have gone with is:

<tbody ng-repeat="thing in things"> <tr ng-repeat="otherThing in thing.otherThings"> <td>{{thing.name}}</td> <td>{{otherThing.foo}}</td> </tr> </tbody> 

This generates multiple tbody elements, one per parent item in my object:

<tbody> <tr> <td>Bob</td> <td>hello</td> </tr> <tr> <td>Bob</td> <td>bye</td> </tr> </tbody> <tbody> <tr> <td>Sid</td> <td>cake</td> </tr> <tr> <td>Sid</td> <td>fish</td> </tr> </tbody> 

I want to avoid multiple tbody elements, but I know in order to access both parent and child items, I will have to nest the ng-repeat's.

I could flatten the original object so that the parent information is duplicated for each child, but I want to avoid this if possible and use the data structure as is.

Are there any special uses of ng-repeat, e.g. multiple expressions that could be used on one ng-repeat to give access to both parent and child items in each iteration?

Thanks

UPDATE

The reason I want to avoid multiple tbody elements is because I have a css selector for alternate row shading:

tbody tr:nth-child(odd){ background-color: $theme-list-alt; } 

If each parent only had one child item they would all get coloured the same, whereas I want alternate row colours across throughout.

Update 2

I wondered whether using ng-repeat-start and ng-repeat-end could help me here, so I tried with the following Plunkr

This doesnt give me a row per child, e.g:

Bob hello Bob bye Sid cake Sid fish 

I can see why, just not sure how I can achieve this.

5
  • Use ng-repeat on <tr> not on <tbody> Commented Jul 12, 2016 at 10:32
  • I already am in my example Commented Jul 12, 2016 at 10:33
  • but one is on tbody I meant that also on tr Commented Jul 12, 2016 at 10:35
  • I want to avoid multiple tbody elements >> why? Commented Jul 12, 2016 at 10:51
  • @mindparse, can you please see my answer? Commented Jul 12, 2016 at 18:23

1 Answer 1

2

Try this.

 <tbody> <tr ng-repeat="thing in things"> <td>{{thing.name}}</td> <td ng-repeat="otherThing in thing.otherThings">{{otherThing.foo}}</td> </tr> </tbody> 
Sign up to request clarification or add additional context in comments.

3 Comments

'Try this'... why? what have you done? what was the problem?
This does not give the desired output I am looking for. I want one row per child item, but the contents of the row should use both parent and child item properties
Sorry, I thought you answer was what I needed but turns out not. I have added a plunkr to my original post which should demonstrate what I'm trying to achieve, see my second update

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.