javascript - 使用 AngularJS 1.7 中的组件在 NgRepeat 中正确渲染 HTML

标签 javascript html angularjs

我有一个简单的应用程序,它在表格中显示水果及其颜色。有一个表组件和行组件。表格组件的 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>

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

table-component

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

最佳答案

一个简单的解决方案是将组件转换为指令并将其作为属性添加到 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 更合适的名称会更好,因为它不是一个不再是组件了。

关于javascript - 使用 AngularJS 1.7 中的组件在 NgRepeat 中正确渲染 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54427943/

相关文章:

javascript - 控制 HTML5 中显示的 PDF 字体

javascript - angular 指令突出显示 div 中的任何输入是否具有焦点

javascript - Angular Controller 继承/覆盖 "superclass"方法

Javascript数组按时间排序html表

javascript - 如何将作用域添加到 angular.js 中的 http Controller ?

jquery - Bootstrap nav - 在桌面上保持展开并在移动设备上折叠

html - 我怎样才能去除云和边界之间的空白区域?

javascript - Angular 翻译服务: HTML tags in string

javascript - 分解函数表达式 - 与几行/参数作斗争

javascript - 在 safari mobile 上播放(和重播)声音