在指令中使用 ng-show

Using ng-show in directive

我正在尝试完成以下行为:

  1. 使用 ng-repeat 遍历一个数组,得到 table 行。
  2. 在每行之后添加一个额外的隐藏行("details")(不能使用多个 tbody 元素)

我做了一个指令,它是 tr 标签的一个属性。第二行已生成但未隐藏。一切都按预期工作,除了 ng-show 不工作并且显示 "detail" 行。

我的指令:

'use strict';
app.directive('entryDetails', function () {
    return {
        restrict: 'A',
        scope: {
            entry: '=',
        },
        link: function(scope,element,attrs) {
            scope.entry.showDetails = false;
            element.after(angular.element('<tr class="entry-details" ng-show="entry.showDetails" id="entry-details-'+scope.entry.id+'"><td colspan="5">Details...</td></tr>'));
        }
    };
});

调用方式:

<tr ng-repeat="entry in  entries track by entry.id" id="entry-{{entry.id}}" entry-details entry="entry">

我需要做什么才能使 ng-show 像在模板中一样工作?

提前致谢!

您需要 $compile 第二个 <tr>

app.directive('entryDetails', function ($compile) {
    return {
        restrict: 'A',
        scope: {
            entry: '=',
        },
        link: function(scope,element,attrs) {
            scope.entry.showDetails = false;
            var t = '<tr class="entry-details" ng-show="entry.showDetails" id="entry-details-'+scope.entry.id+'"><td colspan="5">Details...</td></tr>';
            element.after(angular.element($compile(t)(scope)));
        }
    };
});

这将允许 Angular 连接 ng-show 并在幕后做所有它必须做的事情以了解它。否则,Angular 不知道它存在。