[英]Rendering HTML Correctly In NgRepeat using Components in AngularJS 1.7
I have a simple app which displays a fruit and its color inside a table.我有一个简单的应用程序,可以在表格中显示水果及其颜色。 There is a table component and row component.
有一个表组件和行组件。 The table component's HTML looks like this:
表格组件的 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>
The row component's HTML looks like this: row 组件的 HTML 如下所示:
<tr>
<td>{{$ctrl.fruit.name}}</td>
<td>{{$ctrl.fruit.color}}</td>
</tr>
As you can see, the table component has an ngRepeat directive on the row component.如您所见,表组件在行组件上有一个 ngRepeat 指令。 The problem is that rendered markup looks like this:
问题是呈现的标记如下所示:
<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>
The browser doesn't know how to handle the row-component tag and the table ends up looking like this:浏览器不知道如何处理 row-component 标签,表格最终看起来像这样:
What do I need to do to get the rows to render correctly?我需要做什么才能使行正确呈现? I have the full CodePen code here .
我这里有完整的CodePen 代码。
A simple solution would be to convert your component to a directive and add it to a tr element as an attribute一个简单的解决方案是将您的组件转换为指令并将其作为属性添加到 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>
NOTE: i left the name of the component as is to be better understandable in your example, it would be better if you changed it to something more appropriate than row-component
since it is not a component anymore.注意:为了在您的示例中更好地理解,我保留了组件的名称,如果您将其更改为比
row-component
更合适的名称会更好,因为它不再是一个组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.