AngularJS嵌套指令被插入其假定的父元素之外 [英] AngularJS nested directives are inserted outside their supposed parent element

查看:84
本文介绍了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

推荐答案

问题与 - 标签。在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 -directive to '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嵌套指令被插入其假定的父元素之外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆