【问题标题】:Create a table with rowspan using a template on an angularjs directive使用 angularjs 指令上的模板创建具有行跨度的表
【发布时间】:2023-03-27 00:25:01
【问题描述】:

我创建了一个自定义指令来输出一个相当简单的表格数据。这是我当前的代码:

app.directive('searchResult', function () {
    return {
        restrict: 'E',
        scope: { content: '=' },
        link: function (scope, element, attrs) {
            var html = '<table class="table table-bordered">';
            angular.forEach(scope.rows, function (row, index) {
            if (row.names.length > 1) { 
               var names = row.names;
                html += '<tr>';
                html += '<td rowspan='+row.names.length+'>'+row.num +'</td>';
                html += '<td>'+names[0] + '</td>';
                html += '</tr>'

                for (var i = 1; i < names.length; i++) {
                   html += '<tr>';
                   html += '<td>'+names[i] +'</td>';
                   html += '</tr>';
                }
           } else {
                html += '<tr>';
                html += '<td>'+row.num +'</td>';
                html += '<td>'+row.names[0] + '</td>';
                html += '</tr>';
        }
        })
        html += '</table>';
        element.replaceWith(html)
        }
    }
});

这段代码的问题在于绑定。如果用户搜索新项目,该指令将在先前显示的结果之上创建一个新表,而不是替换旧结果。

我正在尝试使用 templateUrl 并有一个包含 {{content}} 的模板并且绑定有效。旧的搜索结果被新的取代。

有没有办法在模板中执行此表代码创建?

【问题讨论】:

    标签: angularjs templates html-table directive


    【解决方案1】:

    在完成 html 后使用 $compile 服务。

    $compile

    代替:

    element.replaceWith(html)
    

    试试:

    html = $compile(html);
    

    它应该保留所有 Angular.js 绑定。但是,这不是一个好习惯,因为您会强制进行额外的范围刷新。

    【讨论】:

    • 谢谢!我可以知道最佳做法是什么吗?
    • 创建外部模板,使用 ng-repeat。 Dont concate strings inside your javascript. Dont 使用 forEach 使用 for 循环和你的大脑。 jsperf.com/for-vs-foreach/37
    • 知道了。我不知道你可以用 ng-repeat 做到这一点。谢谢!
    【解决方案2】:

    我通过以下代码使用模板解决了我的情况:

    <table class="table table-bordered">
        <tbody>            
            <tr ng-repeat-start='myEntry in content'>
                <td rowspan="{{myEntry.names.length}}">{{myEntry.num}}</td>
                <td>{{myEntry.names[0]}}</td>
            </tr>
            <tr ng-repeat-end ng-repeat='name in myEntry.names' ng-if="$index > 0">
                <td>{{name}}{{myEntry.names}}</td>
            </tr>
        </tbody>
    </table>
    

    部分代码来自 SO 中的链接:

    感谢 Michał Lach 指出一种更优雅的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-29
      • 2017-07-22
      • 1970-01-01
      • 2015-03-17
      • 1970-01-01
      相关资源
      最近更新 更多