嵌套Angular指令的奇怪行为
-
20-12-2019 - |
题
我想在其他指令中使用我的指令。下面的例子给出了如此奇怪的结果,我不得不放弃并提出这个问题。我希望有人向我解释这里发生了什么:
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/
是bug吗?
编辑:
预期输出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
而不是真的在一个和两个。(让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标签包围以摆脱 自动生成的跨度.
这是更新的小提琴: http://jsfiddle.net/WPpUL/7/
其他提示
带根元素的包装模板将解决问题
template: '<div><outer>one</outer></div>'
template: '<div><outer>two</outer></div>'
. 不隶属于 StackOverflow