挑战用ng-repeat重复tr

rol*_*and 14 angularjs angular-ui angularjs-directive angularjs-ng-repeat

我正在努力解决一个特殊的用例.我在底部为您提供了一个jsfiddle代码段.

1. HTML表格

我的HTML是一张桌子.ng-repeat指令必须应用于html元素.在我的用例中,这不能完成,因为ng-repeat的实例由double tr元素组成:

<!-- ng-repeat the following block n times -->
<tr>
 <td>text</td>
</tr>
<tr>
 <td tooltip="comment that is bound to the first tr">hover me</td>
</tr>
Run Code Online (Sandbox Code Playgroud)

AngularJS不提供语法ng-repeat注​​释(与KnockoutJS不同).我在SO上发现了类似的问题.但是,用例包括在元素中附加HTML.我将在ng-repeated tr之后放置一个新的tr,但它只是不起作用.此外,还有一些新的东西需要考虑.

2. Tooltip指令

第二个tr嵌入了一个tooltip指令,该指令取自angular-ui-bootstrap.因此,纯jQuery方法可能不可行.

3.我的目标

我为您提供了一个完全不使用ng-repeat的代码片段.我的目标是使用ng-repeat应用于我的集合的每个元素.

http://jsfiddle.net/RkCMr/1/

akn*_*akn 42

它也可以用ng-repeat-startng-repeat-end指令来做:

<table>
  <tr ng-repeat-start="item in items">
    <td>first</td>
    <td>row</td>
  </tr>
  <tr ng-repeat-end>
    <td>second</td>
    <td>row</td>
  </tr>
</table>
Run Code Online (Sandbox Code Playgroud)

在我看来,它比重复tbody元素要好得多.

  • ^^^^^这是一个比接受的答案更好的解决方案.不要重复`tbody`! (4认同)

Dav*_*Lin 33

您可以使用tbody标记将多个tr拼接在一起并使用ngRepeat循环遍历它.

http://jsfiddle.net/RkCMr/4/

<div ng-app="challenge">
    <h3>how can I refactor it out using ng-repeat?</h3>
    <table ng-controller="ctrl">
        <thead></thead>         
        <tbody ng-repeat="item in collection">
            <tr ng-click="showing=!showing">
                <td>click</td>
                <td>{{item}}</td>
            </tr>
            <tr ng-show="showing">
                <td>--></td>
                <td>comment {{item}}
                    <a tooltip="a tooltip comment {{item}}">
                        <i class="icon-ok-sign"></i>
                    </a>
                </td>                
            </tr>
        </tbody> 
    </table>    
</div>
Run Code Online (Sandbox Code Playgroud)

顺便说一句,看起来你的代码仍然是Jquery的做事方式.即使你把它们放在一个指令中.如上例所示,根本不需要指令,也不使用JQuery.