javascript - AngularJS 嵌套指令被插入到它们假定的父元素之外

标签 javascript angularjs angularjs-directive angularjs-ng-repeat

我无法理解嵌套指令如何与 AngularJS 一起工作。

var app = angular.module('plunker', []);

app.directive('myTable', function() {
    return {
        restrict: 'E',
        template: [
            '<table class="table table-query" ng-show="queries.length">',
                '<thead>',
                    '<tr>',
                        '<th class="query-name">Name</th>',
                        '<th class="query-status">Status</th>',
                    '</tr>',
                '</thead>',
                '<tbody>',
                    '<my-row ng-repeat="query in queries track by $index"',
                             'query="query">',
                    '</my-row>',
                '</tbody>',
            '</table>',
        ].join(''),
        scope: {
            queries: '='
        },
        controller: function() {
        },
        link: function(scope, element) {
        }
    };
});

app.directive('myRow', function() {
    return {
        restrict: 'E',
        template: [
            '<tr class="query query-status-{{query.status}}">',
                '<td>{{ query.name }}</td>',
                '<td>{{ query.status | uppercase }}</td>',
            '</tr>',
        ].join(''),
        scope: {
            query: '='
        },
        replace: true
    };
});

有人可以向我解释为什么 tr 显示在 tbody 之外吗? 我只想在表指令中嵌套一个行指令。我很确定我在某处遗漏了 ng-transclude 但在哪里?我已经检查了 angular-bootstrap,它们似乎在 compile 功能上发挥了一些作用。非常感谢任何帮助。

See this corresponding plunkr .

最佳答案

问题与 table 标签有关。浏览器在 angularjs 呈现之前重新排列 myTable 模板的 html。这是因为 html 无效。

要解决此问题,您可以将 myRow 指令的限制属性更改为 'A' 并像这样使用指令:

...
'<tbody>',
    '<tr my-row ng-repeat="query in queries track by $index"',
        'query="query">',
    '</tr>',
'</tbody>',
...

这样浏览器就会看到有效的 html 并且它会像它应该的那样工作。

这是固定的 plunkr .

关于javascript - AngularJS 嵌套指令被插入到它们假定的父元素之外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27448789/

相关文章:

javascript - Angular Material datepicker 过滤器特定日期

javascript - 用于更新 IFrame 主体的 AngularJS 指令

javascript - 先前单击下一个按钮时,clickNextButton 未正确执行

javascript - 过滤树结构

javascript - 如何在 ES6 中导入嵌套对象

javascript - 按 AngularJS 中的原样打印页面

javascript - 通过查询字符串加载 mp4 视频

javascript - Angular 1.3 - 将 Id 添加到 ng-options 内的选项标签

javascript - Angular ng-重复数学

javascript - 从 Angular.js 中的指令 Controller 调用工厂