gpt4 book ai didi

javascript - 嵌套 Angular 指令的奇怪行为

转载 作者:行者123 更新时间:2023-11-30 17:46:42 25 4
gpt4 key购买 nike

我想在其他指令中使用我的指令。下面的例子给出了如此奇怪的结果,我不得不放弃并提出这个问题。我希望有人向我解释这里发生了什么:

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:

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

生成的 DOM 是:

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

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

这是一个错误吗?

编辑:

预期输出 DOM:

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

最佳答案

而不是使用 replace 我们将手动完成它 - 这似乎让 angular 快乐并得到你需要的东西。

1) 在一和二中设置 replace: false 而不是 true。 (让 Angular 快乐)

2) 使用此链接功能手动将 html 替换为一和二:

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

这将导致:

<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>

文本节点已经被B标签包围,去掉了automatically generated SPANs .

这是更新后的 fiddle :http://jsfiddle.net/WPpUL/7/

关于javascript - 嵌套 Angular 指令的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20003840/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com