AngularJS:如何正确transclude定制指令子元素? [英] AngularJS : How to properly transclude child elements in custom directive?

查看:125
本文介绍了AngularJS:如何正确transclude定制指令子元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是一些code: rel=\"nofollow\">链接

Here's some code : link

我试图创建一个包装它的孩子们在一些样板指令。但是,如果孩子有 NG-如果控制自己的外表,transclusion不工作。那么这类型的呢,但你可以看到 NG-如果逻辑没有得到通过正确地传递。

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.

推荐答案

问题是角开始取代 ngIf 与它评论用于跟踪在何处放置条件code。这是最容易看到的例子。

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.

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

貌似这个你transclude功能的克隆变量( transclude(函数内(克隆){

<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');

既然你只transcluding符合上述过滤器的 ngIf 注释丢失的元素。

解决方案是过滤征求意见,以及在你的追加添加它们(所以角保持它的参考点到 ngIf )。做到这一点的方法之一是用它来取代上述(使用的事实,HTML注释是节点类型8)

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

工作plunker

这篇关于AngularJS:如何正确transclude定制指令子元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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