AngularJS:如何在自定义指令中正确嵌入子元素? [英] AngularJS : How to properly transclude child elements in custom directive?
问题描述
这是一些代码:link
我正在尝试创建一个指令,将其子项包装在一些样板中.但是如果孩子们有 ng-if
控制他们的外表,嵌入"就不起作用.嗯,确实如此,但正如您所看到的,ng-if
逻辑没有正确传递.
我想知道如何修复它,以及 Angular 文档中描述的位置(如果有的话).
问题 是 Angular 最初将 ngIf
替换为它用来跟踪放置位置的注释条件代码.举个例子最容易看出来.
您的 HTML:
<label>测试</label><input type="text" ng-model="editing.name"/><span class="text-error" ng-if="editing.name.length != 3">名称必须为 3 个字符 </span>
在您的 transclude 函数的 cloned
变量中看起来像这样 (transclude(function (cloned) {
):
<label>测试</label><input type="text" ng-model="editing.name" class="ng-valid ng-dirty"><!-- ngIf:editing.name.length != 3 -->
因此,您正在过滤的具有类 text-error
的元素(如下)不在 cloned
中.只是评论在那里.
var inputAndMessages = cloned.filter('input, button, select, .text-error');
由于您只转置了与上述过滤器匹配的元素,ngIf
注释将丢失.
解决方案也是过滤评论并将它们添加到您的附加内容中(因此 Angular 保持它对 ngIf
的引用点).一种方法是用这个替换上面的(使用 html 注释是节点类型 8 的事实)
var messages = cloned.filter(function(){ return this.nodeType == 8; });//注释var input = cloned.filter('输入,按钮,选择')var inputAndMessages = input.add(messages);
Here's some code : link
I'm trying to create a directive that wraps its children in some boilerplate. But if the children have ng-if
controlling their appearance, the "transclusion" doesn't work. Well it sort of does, but as you can see the ng-if
logic is not getting passed through correctly.
I'd like to know how to fix it, but also where (if anywhere) this is described in the Angular docs.
The problem is that Angular initially replaces ngIf
with a comment that it uses to track where to place the conditional code. It's easiest to see with an example.
Your HTML:
<div control-group>
<label>Test</label>
<input type="text" ng-model="editing.name" />
<span class="text-error" ng-if="editing.name.length != 3"> Name must be 3 characters </span>
</div>
Looks like this inside your transclude function's cloned
variable (transclude(function (cloned) {
):
<div control-group>
<label>Test</label>
<input type="text" ng-model="editing.name" class="ng-valid ng-dirty">
<!-- ngIf: editing.name.length != 3 -->
</div>
So, the element with class text-error
that you're filtering on (below) isn't in cloned
. Just the comment is there.
var inputsAndMessages = cloned.filter('input, button, select, .text-error');
Since you're only transcluding elements that match the above filter the ngIf
comment is lost.
The solution is to filter for comments as well and add them in your append (so Angular maintains it's reference point to the ngIf
). One way to do that is to replace the above with this (using the fact that an html comment is node type 8)
var messages = cloned.filter(function(){ return this.nodeType == 8; }); //comments
var inputs = cloned.filter('input, button, select')
var inputsAndMessages = inputs.add(messages);
这篇关于AngularJS:如何在自定义指令中正确嵌入子元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!