【问题标题】:Rendering HTML Correctly In NgRepeat using Components in AngularJS 1.7使用 AngularJS 1.7 中的组件在 NgRepeat 中正确呈现 HTML
【发布时间】:2023-04-07 17:48:01
【问题描述】:

我有一个简单的应用程序,它在表格中显示水果及其颜色。有表格组件和行组件。表格组件的 HTML 如下所示:

<table class="table table-condensed">
  <thead>
    <tr>
      <th>Fruit</th>
      <th>Color</th>
    </tr>
  </thead>
  <tbody>
    <row-component fruit="fruit" ng-repeat="fruit in $ctrl.fruits"></row-component>
  </tbody>
</table>

行组件的 HTML 如下所示:

<tr>
  <td>{{$ctrl.fruit.name}}</td>
  <td>{{$ctrl.fruit.color}}</td>
</tr>

如您所见,表格组件在行组件上有一个 ngRepeat 指令。问题是渲染的标记看起来像这样:

<table-component class="ng-isolate-scope"><!-- ngRepeat: fruit in $ctrl.fruits --><row-component fruit="fruit" ng-repeat="fruit in $ctrl.fruits" class="ng-scope ng-isolate-scope"><tr>
  <td class="ng-binding">Apple</td>
  <td class="ng-binding">Red</td>
</tr></row-component><!-- end ngRepeat: fruit in $ctrl.fruits --><row-component fruit="fruit" ng-repeat="fruit in $ctrl.fruits" class="ng-scope ng-isolate-scope"><tr>
  <td class="ng-binding">Banana</td>
  <td class="ng-binding">Yellow</td>
</tr></row-component><!-- end ngRepeat: fruit in $ctrl.fruits --><row-component fruit="fruit" ng-repeat="fruit in $ctrl.fruits" class="ng-scope ng-isolate-scope"><tr>
  <td class="ng-binding">Pear</td>
  <td class="ng-binding">Green</td>
</tr></row-component><!-- end ngRepeat: fruit in $ctrl.fruits --><table class="table table-condensed">
  <thead>
    <tr>
      <th>Fruit</th>
      <th>Color</th>
    </tr>
  </thead>
  <tbody>

  </tbody>
</table></table-component>

浏览器不知道如何处理行组件标签,表格最终看起来像这样:

我需要做什么才能正确呈现行?我有完整的CodePen code here

【问题讨论】:

  • 这个问题详细介绍了很多可以使用的方法stackoverflow.com/q/49919207/5746996
  • 如果在组件上添加transclude: true 会发生什么?
  • 将 transclude 设置为 true 没有任何作用。我早些时候尝试过,希望它会。

标签: javascript html angularjs


【解决方案1】:

一个简单的解决方案是将您的组件转换为指令并将其作为属性添加到 tr 元素中

<table class="table table-condensed">
  <thead>
    <tr>
      <th>Fruit</th>
      <th>Color</th>
    </tr>
  </thead>
  <tbody>
    <tr row-component fruit="fruit" ng-repeat="fruit in $ctrl.fruits"></tr>
  </tbody>
</table>

注意:我留下了组件的名称,以便在您的示例中更好地理解,如果您将其更改为比row-component 更合适的名称会更好,因为它不再是一个组件。

【讨论】:

  • 如果在行组件中删除tr 并只使用td,这是一个很好的答案
  • 你也可以将 row-component 重命名为 tr 它也可以。
  • @Maher 调用组件根据标准假定至少包含 1 个连字符,以防止试图覆盖原生 html 元素。
  • 在做了一些研究后,我得出结论,嵌入最好与指令而不是组件一起使用。
猜你喜欢
  • 2016-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 2020-02-19
  • 2018-11-09
相关资源
最近更新 更多