在2015年的演讲中,他们谈到了用web组件和Angular(具体链接到与此问题相关的时间)ng conf创建内容容器组件,并讨论了创建和匹配多个插入点的指令组件。(创建与web组件插入实现匹配的行为)。20分钟的谈话很彻底,但他们似乎有点悬着不放。例如,
// this being the html page
<my-site-container>
<div t-to="menu">
this displays in the menu/nav of the directive component.
</div>
<div t-to="body">
this displays in the body/main of the directive component.
</div>
</my-site-container>
// directive template
`<div id="site-container>
<nav t-id="menu"></nav>
<main t-id="body"></main>
</div>"`
它需要链接函数中的自定义代码。(仅使用ng transclude的transclusion不允许插入点的"匹配"。有关更多信息,请参阅视频。)问题是它们在DDO中的链接功能代码:
return {
transclude: true,
template: ...,
link: function(scope, elem, ctrl, transclude) {
transclude(function(clone) {
angular.forEach(clone, function(cloneEl)
var tId = cloneEl.attributes["t-to"].value;
var target = elem.find('[t-id="' + tId + '"]');
target.append(cloneEl);
});
}
};
这对我来说并不完全奏效。这是砰的一声。问题1。过滤掉具有t-to属性的元素的最佳方法是什么?
当使用传统的标记结构表示时,var tId = cloneEl.attributes["t-to"].value;
是未定义的
// the forEach supplies empty-like node, <div..., empty-like node, <div...
<my-directive>
<div t-to="menu">I render in the menu.</div>
<div t-to="body">I render in the body.</div>
</my-directive>
//this for Each提供正确且仅提供所需的div我在菜单中渲染。我在身体里渲染。//因此,似乎传统的html结构在迭代时会将空间添加为空文本节点。
我在plunk中使用了if (cloneEl.attributes) {var tId = ...}
,这似乎适用于
问题2:在指令模板中获取具有特定名称和属性值的元素的最佳方法是什么?
var target = elem.find('[t-id="' + tId + '"]');
这段代码似乎没有意义,它会起作用,对我来说也不合适。(注意:elem相当于模板或temp
,因为他们在代码示例中似乎有它。)
find
方法他们是如何使用的?它们似乎是按属性名称和值查找元素。我四处查找[]
语法,但找不到任何引用。角度将查找限制为标记名称。他们没有提到jQuery,但jQuery似乎也没有这个功能。
您需要在angular之前在索引中导入jquery。之后,find()应该可以工作了。