3

我知道我可以使用foreach淘汰赛中的评论向列表添加条件。但是如果observableArray空,我想在表中添加一个默认行。

目前我做这样的事情:

<table>
    <!-- ko foreach: members -->
    <tr>
        <td data-bind="text: Id"></td>
        <td data-bind="text: FirstName"></td>
        <td data-bind="text: LastName"></td>
    </tr>
    <!-- /ko -->
    <tr data-bind="if: MemberCount == 0">
        <td colspan="3">
            No members have been added yet
         </td>
    </tr>
</table>

有没有更优雅的方式?

4

3 回答 3

4

我同意 0lukasz0 评论,并会在视图模型上执行计算属性:

  model.hasNoMembers = ko.computed(function(){
    return model.members().length === 0;
  });

html:

<table>
    <!-- ko foreach: members -->
    <tr>
        <td data-bind="text: Id"></td>
        <td data-bind="text: FirstName"></td>
        <td data-bind="text: LastName"></td>
    </tr>
    <!-- /ko -->
    <tr data-bind="if: hasNoMembers">
        <td colspan="3">
            No members have been added yet
         </td>
    </tr>
</table>
于 2013-06-03T18:55:11.277 回答
3

这样的事情将消除对任何条件注释的需要,仅使用数据绑定:

<tbody data-bind="foreach: members">
  <tr>
    <td data-bind="text: Id"></td>
    <td data-bind="text: FirstName"></td>
    <td data-bind="text: LastName"></td>
  </tr>
</tbody>
<tfoot data-bind="if: (memberCount == 0)">
 <tr>
    <td colspan="3">
        No members have been added yet
     </td>
</tr>
</tfoot>
于 2013-06-03T18:51:45.630 回答
1

那这个呢:

<table>           
    <tbody data-bind="foreach: members"> 
        <tr>
            <td data-bind="text: Id"></td>
            <td data-bind="text: FirstName"></td>
            <td data-bind="text: LastName"></td>
        </tr>
    </tbody>   

    <tbody data-bind="if: members().length == 0">
        <tr>
            <td colspan="3">No members have been added yet</td>
        </tr>
    </tbody>    
</table>

关于 jsFiddle 的证明:http: //jsfiddle.net/fkQQ2/

于 2013-06-03T19:46:16.507 回答