我一直试图弄清楚如何使用指令和数据数组生成表。基本上我希望能够像这样构建我的HTML:
<div ng-init="myData = [name: 'John', age: 22]"></div>
<dynamic-table data="myData">
<field title="column 1" class="myClass" expression="{{object.name}}" />
<field title="column 2" class="myClass" expression="{{object.age}}" />
</dynamic-table>
从那个html,我希望我的指令生成以下HTML:
<table>
<tr>
<th>column 1</th>
<th>column 2</th>
</tr>
<tr>
<th>John</th>
<th>22</th>
</tr>
</table>
问题是我需要在指令内部计算表达式{{object.name}},而不是在开始传入指令之前。我有一个jsfiddle here来证明这个问题。我也有兴趣了解任何其他方法来实现这一目标。我已经尝试使用编译指令函数,但最终你遇到了与表达式相同的事情。当然,我可以使用ng-repeats来做到这一点,但我的指令最终会做的不仅仅是这个。
以下是小提琴的指示:
var appModule = angular.module('app', [])
.directive('dynamicTable', function () {
return {
restrict: 'E',
replace: true,
transclude: true,
template:
'<table>' +
'<tr>' +
'<th ng-repeat="field in fields">{{field.title}}</th> ' +
'</tr>' +
'<tr ng-repeat="object in data" ng-transclude>' +
'<td ng-repeat="field in fields">' +
'{{field.expression}}' +
'</td>' +
'</tr>' +
'</table>',
scope: {
data: '='
},
controller: function ($scope) {
$scope.fields = [];
}
};
}).directive('field', function () {
return {
restrict: 'E',
require: '^dynamicTable',
link: function (scope, element, attrs, controller) {
var exists = false;
for (var idx = 0; idx < scope.fields.length; idx++) {
if (scope.fields[idx].title === attrs.title) {
exists = true;
break;
}
}
if (!exists) {
scope.fields.splice(0, 0, { title: attrs.title, 'class': attrs.class, expression: attrs.expression });
}
}
};
});