【问题标题】:How to use ng-if with table to display td based on the condition如何使用 ng-if 和 table 根据条件显示 td
【发布时间】:2014-06-21 08:42:46
【问题描述】:

参考 DIV 中有关 ng-if 的较早帖子 参考此处给出的链接 :: Ng-If within DIV ,但是当我尝试使用 ng-if inside table 和 ng-repeat 进行相同操作时在 td 上似乎效果不佳。如果我错了,请纠正我我做了 2 次尝试根据条件显示列,但没有一个有效。下面我给出了代码供参考。有人可以帮我解决这个问题。如果您需要更多说明,请告知。

HTML

试试 :: 1

   <table>
        <tr ng-repeat = "data in comments">
            <td ng-if="data.type == 'hootsslllll' ">
             //differnt template with hoot data
            </td>
            <td ng-if="data.type == 'story' ">
             //differnt template with story data
            </td>
            <td ng-if="data.type == 'article' ">
            //differnt template with article data
            </td>
        </tr>

    </table>

试试 :: 2

<table>
    <tr ng-repeat = "data in comments">
        <div ng-if="data.type == 'hootsslllll' ">
            <td> //differnt template with hoot data </td>
        </div>
        <div ng-if="data.type == 'story' ">
            <td> //differnt template with story data </td>
        </div>
        <div ng-if="data.type == 'article' ">
            <td> //differnt template with article data </td>
        </div>
    </tr>
</table>

【问题讨论】:

  • it doesn't seems to work well. 你能详细说明一下吗?它(不)做什么?
  • 表格有时不喜欢 trs 中的 div。尝试删除 div,并将 ng-if 表达式直接放入 td 标签中。
  • @ZackArgyle 在我的第一次尝试中我做了同样的事情,但它不起作用
  • @: Tim Castelijns 需要根据条件显示列
  • ngIf 根据条件添加和删除 dom 节点,您可能想尝试使用 ngShowngHide 来代替将相关元素设置为 display: none

标签: angularjs angular-ng-if


【解决方案1】:

ng-if 应该适用于您的 try::1。这是小提琴的工作示例

http://jsfiddle.net/shivaraj/n3xWB/

【讨论】:

    【解决方案2】:

    如果表格结构的格式不正确,大多数浏览器都会忽略表格结构中的任何其他 DOM 元素。这意味着,在上面的代码中,tr 中不能有 div 标记。试试这个

    <table>
      <tr ng-repeat = "data in comments">
        <td ng-if="data.type == 'hootsslllll' "> //differnt template with hoot data </td>
        <td ng-if="data.type == 'story' "> //differnt template with story data </td>
        <td ng-if="data.type == 'article' "> //differnt template with article data </td>
      </tr>
    </table>
    

    【讨论】:

      【解决方案3】:

      避免使用 inside 以遵守更好的浏览器语义。此外,如果要确保相等表达式的 RHS 上的值的类型,则在检查相等时,'===' 可能是一个更好的选择。

      这适用于 &lt;table&gt;&lt;div&gt; 单独

      <div ng-controller="tableCtrl">
              <div ng-repeat="data in comments">
                  <div ng-if="data.type === 'hootsslllll' ">//differnt template with hoot data</div>
                  <div ng-if="data.type === 'story' ">//differnt template with story data</div>
                  <div ng-if="data.type === 'article' ">//differnt template with article data</div>
              </div>
      </div>
      

      http://jsfiddle.net/Mu6T6/3/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-25
        • 1970-01-01
        相关资源
        最近更新 更多