我有一个简单的应用程序,它在表格中显示水果及其颜色。有一个表组件和行组件。表格组件的 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 。
最佳答案
一个简单的解决方案是将组件转换为指令并将其作为属性添加到 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/