2

我一直在试图弄清楚如何使用指令和数据数组生成表。基本上我希望能够像这样构造我的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 来演示这个问题。我也很想听听任何其他方法来实现这一点。我已经尝试过使用编译指令函数,但最终你遇到了与表达式相同的事情。当然,我可以使用 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 });
            }
        }
    };
});
4

0 回答 0