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

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

本文介绍了AngularJS 嵌套指令被插入到它们假定的父元素之外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解嵌套指令如何与 AngularJS 配合使用.

I'm having trouble understanding how nested directives work with 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 之外?我只想做的是在 table 指令中嵌套一个 row 指令.我很确定我在某处遗漏了 ng-transclude 但在哪里?我已经检查了 angular-bootstrap,它们似乎对 compile 函数有点影响.非常感谢任何帮助.

Can someone explain to me why the tr are diplayed outside the tbody?What I simply want to do is nest a row directive inside a table directive. I'm pretty sure I'm missing a ng-transclude somewhere but where? I've checked angular-bootstrap and they seem to play a bit with compile function. Any help is much appreciated.

查看相应的 plunkr.

推荐答案

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

The problem has to do with the table-tag. The browser rearranges the html of the myTable template before angularjs renders it. This is happening because the html is not valid.

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

To solve this issue you can change the restrict property of the myRow-directive to 'A' and use the directive like this:

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

这样浏览器就会看到有效的 html 并且它的工作方式应该是这样.

This way the browser sees valid html and it works like it should be.

这是固定的 plunkr.

Here is the fixed plunkr.

这篇关于AngularJS 嵌套指令被插入到它们假定的父元素之外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 03:37