0

Let's say that I have a simple loop like

<div ng-repeat="item in items">{{item.foo}}<br></div>

or

<div ng-repeat="item in items" ui-view="itemView"></div>

How can I avoid rendering defining tag (div) to get:

Foo 1<br>
Foo 2<br>
Foo 3<br>

instead of:

<div>Foo 1<br></div>
<div>Foo 2<br></div>
<div>Foo 3<br></div>

What for: I need this i.e. to creating table rows where wrapping <tr> with div is not allowed, YES I know that I can use <tr ng-repeat=... for simple cases, anyway I'd prefer to move rendering tr tag into itemView as well (I have several conditions to check for adding i.e. proper CSS classes, otherwise I'll need to add these classes into each td in row)

biesior
  • 55,576
  • 10
  • 125
  • 182
  • Why not an ul instead? This is allowed inside table, and you can avoid the awkward
    tag. I never saw a default behavior of ng-repeat without an element. You can create a custom directive to override the div as well
    – Fals Dec 22 '14 at 15:50
  • @Fals `br` is just a sample, `tr` is my current case (and maybe `ul` will help - need to check, but I'd really would be happy to get possibility of avoiding wrapping it with nesting tag especially when using dedicated views via ui-view. Can you point me how to create custom directive for this simple scenario ? (of course as an answer so guys can upvote it ;) – biesior Dec 22 '14 at 15:58

2 Answers2

2

you can use tbody:

<tbody ng-repeat="item in items">
  <tr>
    <td>{{ item.foo }}</td>
  </tr>
</tbody>
Ilan Frumer
  • 32,059
  • 8
  • 70
  • 84
  • Thank you, your solution is useful and I'll keep in mind for other scenarios with tables (TBH I was sure that table can contain only one `tbody` but spec allows for repeating it. – biesior Dec 22 '14 at 16:43
  • @biesior you can have multiple tbody in one table, check this question: http://stackoverflow.com/questions/4873701/are-html-tables-valid-if-there-are-multiple-tbody-tag-used – Ilan Frumer Dec 22 '14 at 17:13
2

By creating custom directive with replace: true attribute you can replace the original html div with the directive's template

here is an example inspired from the ng-book:

<div my-directive></div>

app.directive('myDirective' function() {
    return {
        template: '<div>my directive without replacement</div>
    }
});

the html will keep the and inject inside it the directive's template like:

<div my-directive>
    <div>my directive without replacement</div>
</div>

But if you set "replace: true" like:

app.directive('myDirective' function() {
    return {
        replace: true
        template: '<div>my directive with replacement<div>'
    }
});

then there will be only the directive's template, which replaced the original

<div>my directive with replacement<div>
Ahmed Hashem
  • 4,675
  • 3
  • 21
  • 28