我试图在多个地方重用HTML视图的一部分。我要重用的部分是HTML表格中的表格单元。问题是我在ng- repeat中的自定义指令正在做有趣的事情。我在jsFiddle上重现了这个问题。jsFiddle中有两个HTML表。第一个是ng- repeat,其中表单元格写在视图中,第二个是表单元格来自指令my- element。Chrome开发人员工具报告,呈现的HTML如下所示。请注意,自定义元素仅出现一次并且在表格外部。
呈现的HTML
<div ng-controller="MyCtrl" class="ng-scope"> table1 <table class="table table-hover"> <tbody><!-- ngRepeat: p in people --> <tr ng-repeat="p in people" class="ng-scope"> <td class="ng-binding">Name: Mike</td> <td class="ng-binding">Age: 20</td> </tr> <tr ng-repeat="p in people" class="ng-scope"> <td class="ng-binding">Name: Peter S</td> <td class="ng-binding">Age: 22</td> </tr> </tbody> </table> <br>table2 <my-element class="ng-binding">Name: Age: </my-element> <table class="table table-hover"> <tbody> <!-- ngRepeat: p in people --> <tr ng-repeat="p in people" class="ng-scope"> </tr> <tr ng-repeat="p in people" class="ng-scope"> </tr> </tbody> </table> </div>
源HTML
<div ng-controller="MyCtrl"> table1 <table class="table table-hover"> <tr ng-repeat="p in people"> <td>Name: {{ p.name }}</td> <td>Age: {{ p.age }}</td> </tr> </table> <br/>table2 <table class="table table-hover"> <tr ng-repeat="p in people"> <my-element></my-element> </tr> </table> </div>
源JS
var app = angular.module('myApp', []); app.directive('myElement', function () { return { restrict: 'E', template: '<td>Name: {{ p.name }}</td><td>Age: {{ p.age }}</td>' } }); function MyCtrl($scope) { $scope.people = [{ name: 'Mike', age: 20 }, { name: 'Peter S', age: 22 }]; }
请注意,jsFiddle是一个简单的示例,常识将导致根本不使用指令。但是,我的目标代码有一个更大的模板,我想重复使用。我也尝试过使用“ ng- include”,但结果相似。
<td>众所周知,在这样的指令中,它表现得很奇怪。而是在parent上使用指令<tr>。在此处阅读有关此问题的更多信息:https : //github.com/angular/angular.js/issues/1459
<td>
<tr>
<table> <tr ng-repeat="p in people" my-element></tr> </table>
这是您可以进一步改进指令的方法,以便使其更可重用。
app.directive('myElement', function () { return { scope: { item: '=myElement' }, restrict: 'EA', template: '<td>Name: {{item.name}}</td><td>Age: {{item.age}}</td>' }; });
并传递item像这样的值:
item
<table> <tr ng-repeat="person in people" my-element="person"></tr> </table>