【问题标题】:How to output an array of different elements in a sequence using Angularjs如何使用Angularjs按顺序输出不同元素的数组
【发布时间】:2020-05-30 11:35:25
【问题描述】:

我有生成 HTML 表格行描述的代码,如下所示:

  [
    {element: 'th', content: 'Header 1'},
    {element: 'td', content: 'data 1'},
    {element: 'td', content: 'data 2'},
  ]

我想用 angularjs 输出这些,比如

<tr>
  <td ng-repeat="item in row" >{{item.content}}</td>
</tr>

除了我不知道这如何处理应该是&lt;th&gt; 的元素?

(例如,Vuejs 有 &lt;td v-is="item.element"&gt;{{item.content}}&lt;/td&gt;,但我正在使用 angularjs 应用程序,所以给出这个例子是为了帮助 Vuejs 人理解我的需要。)

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    感谢Clint's answer,一个适用于表格的变体是:

    创建一个删除自身的指令(!)

    angular.module('theapp').directive('repeatSection', function () {
      return { restrict: 'A', replace: true, link(scope, el) { el.remove(); } };
    });
    

    使用&lt;td&gt;元素包装逻辑:

    <table>
     ...
     <tbody>
       <tr ng-repeat="row in rows">
    
         <td repeat-section ng-repeat-start="cells in row"></td>
         <th ng-if="cell.element === 'th'">{{cell.content}}</th>
         <td ng-if="cell.element === 'td'">{{cell.content}}</td>
         <td repeat-section ng-repeat-end></td>
    
       </tr>
     </tbody>
    </table>
    
    • repeat-section 指令删除作为ng-repeat-start 一部分创建的td 元素。
    • 我们需要在这里使用&lt;td&gt;——如果你使用&lt;div&gt;&lt;repeat-section&gt;,这些元素会被清空(至少在Firefox中),因为&lt;tr&gt;只能包含&lt;td&gt;&lt;th&gt; .
    • 这适用于我的使用(表格单元格),但不是通用解决方案 - 正如您将看到的,我必须包含每个可能的元素之一;在一般情况下会变得混乱。

    【讨论】:

      猜你喜欢
      • 2013-08-28
      • 2021-07-25
      • 2022-11-24
      • 2020-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-15
      • 2015-06-30
      相关资源
      最近更新 更多