简体   繁体   English

嵌套Angular指令的奇怪行为

[英]Strange behavior of nested Angular directives

I want to use my directives within other directives. 我想在其他指令中使用我的指令。 The following example gives so strange results that I had to give up and ask this question. 以下示例给出了非常奇怪的结果,以至于我不得不放弃并提出这个问题。 I would like someone to explain me what is going on here: 我想有人向我解释这是怎么回事:

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

app.directive('one', function() {
    return {
        restrict: 'E',
        replace: true,
        template: '<outer>one</outer>'
    };
});

app.directive('two', function() {
    return {
        restrict: 'E',
        replace: true,
        template: '<outer>two</outer>'
    };
});

app.directive('outer', function() {
    return {
        restrict: 'E',
        replace: true,
        transclude: true,
        template: '<div ng-transclude></div>'
    };
});

HTML: HTML:

    <outer>whatever</outer>
    <one></one>
    <two></two>
    <outer>something</outer>

The resulting DOM is: 产生的DOM为:

    <div ng-transclude=""></div>
    <outer></outer>
    <two></two>
    <outer>something</outer> 

JSFiddle: http://jsfiddle.net/WPpUL/ JSFiddle: http : //jsfiddle.net/WPpUL/

Is it a bug? 是虫子吗?

EDIT: 编辑:

Expected output DOM: 预期的输出DOM:

    <div ng-transclude>whatever</div>
    <div ng-transclude>one</div>
    <div ng-transclude>two</div>
    <div ng-transclude>something</div>

Wrap template with a root element will fix the problem 带有根元素的包装模板将解决此问题

template: '<div><outer>one</outer></div>'
template: '<div><outer>two</outer></div>'

Instead of using replace we'll do it manually- this seems to keep angular happy and gets you what you need. 无需使用replace我们将手动进行操作-这似乎可以使您满意,并满足您的需求。

1) Set replace: false instead of true in One and Two. 1)在“一”和“二”中设置replace: false而不是true。 (making angular happy) (使角度快乐)

2) Manually replace the html using this link function to One and Two: 2)使用此链接功能手动替换html到One和Two:

link: function(scope, element, attrs) {
    element.replaceWith(element.html());
}

This will result in: 这将导致:

<div ng-transclude=""><b class="ng-scope">whatever</b></div>
<div ng-transclude=""><b class="ng-scope">one</b></div>
<div ng-transclude=""><b class="ng-scope">two</b></div>
<div ng-transclude=""><b class="ng-scope">something</b></div> 

The text nodes have been surrounded by B tags to get rid of automatically generated SPANs . 文本节点已被B标签包围,以摆脱自动生成的SPAN

Here's the updated fiddle: http://jsfiddle.net/WPpUL/7/ 这是更新的小提琴: http : //jsfiddle.net/WPpUL/7/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM