这不能回答你的问题,但我认为这是一种更通用的方式来做你想做的事。
首先将要显示的列列表传递给指令:
<custom-table table="data" columns="columns">
</custom-table>
在您的控制器中:
app.controller('MainCtrl', function($scope) {
$scope.data = [
{Username: "Test1", FirstName: "Bill", LastName: "Jones"},
{Username: "Test2", FirstName: "Sophie", LastName: "O'Grady"},
{Username: "Test3", FirstName: "Tim", LastName: "Cross"}
];
$scope.columns = ["Username", "FirstName", "LastName"]
});
在您的指令中:
app.directive('customTable', ['$compile', function($compile){
return {
restrict: 'E',
templateUrl: 'tableTemplate.html',
scope: {
table: '=',
columns: '='
}
};
}]);
最后将您的模板更改为:
<div>
<table>
<thead>
<tr>
<th ng-repeat="col in columns">{{ col }}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in table">
<td ng-repeat="col in columns">
{{ row[col] }}
</td>
</tr>
</tbody>
</table>
</div>
这是更新的 plunker:http ://plnkr.co/edit/dYwZWD2jB2GsmnvmuSbT