挑战用ng-repeat重复tr

时间:2013-08-07 07:39:43

标签: angularjs angularjs-directive angular-ui angularjs-ng-repeat

我正在努力解决一个特殊用例。我在底部为你提供了一个jsfiddle片段。

1。 HTML表格

我的HTML是一张桌子。必须将ng-repeat指令应用于html元素。在我的用例中,这不能完成,因为ng-repeat的实例由双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>

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

2。工具提示指令

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

第3。我的目标

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

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

3 个答案:

答案 0 :(得分:41)

也可以使用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>

在我看来,这比重复tbody元素要好得多。

答案 1 :(得分: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>

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

答案 2 :(得分:2)

以下是此解决方案。

<div ng-app="challenge">
<h3>how can I refactor it out using ng-repeat?</h3>
<table ng-controller="ctrl">
    <thead></thead>
    <tbody ng-repeat="l in collection">
        <tr ng-click="isRowCollapsed=!isRowCollapsed">
            <td>click</td>
            <td>{{l}}</td>
        </tr>
        <tr ng-hide="isRowCollapsed">
            <td>--></td>
            <td>comment {{l}}
                <a tooltip="a tooltip comment {{l}}">
                    <i class="icon-ok-sign"></i>
                </a>
            </td>                
        </tr>            
    </tbody>
</table>    

http://jsfiddle.net/RkCMr/7/