【发布时间】:2025-12-29 21:40:11
【问题描述】:
我正在使用 vanilla AngularJS v1.4.5(无 jQuery),并希望我的自定义指令在编译时为其祖父元素添加一个属性。
在编译函数中,我可以使用element的parent()方法两次获取祖父元素,并使用attr()方法添加我的属性。但是,如果 parent 元素具有 ngIf 指令,则祖父元素不会获得该属性。
angular.module('myApp', [])
.directive('foo', fooDirective)
;
function fooDirective() {
return {
compile : compile,
priority: 601 // ngIf is 600
};
function compile(element, attrs) {
var parent, grandparent;
parent = element.parent();
grandparent = parent.parent();
parent.attr('foo', 'bar');
grandparent.attr('foo', 'bar');
}
}
这是我所知道的:
- 如果父元素上未使用
ngIf,则该属性将添加到祖父元素。 - 该问题不应与
scope相关,因为这是在编译阶段发生的,在作用域与任何元素相关联之前。 - 我的编译函数应该在
ngIf之前运行,它的优先级为600(和doesn't have a compile function)。 -
ngIf完全删除并重新创建 DOM 中的元素(连同其子元素),但这不应影响祖父元素或更改其属性。
如果父元素具有ngIf 指令,谁能向我解释为什么我不能将属性添加到指令的祖父元素?
【问题讨论】:
-
只是为了成为一个坚持不懈的 Angular 默认使用 jqLite 所以无论你喜欢与否你都在使用 jQuery ;)
-
指令通常只处理它们的 DOM 子树。尝试改变祖先是很奇怪的。你也不应该这样做DOM manipilation in compile other than to the template。你的用例是什么?至于
ngIf- 在编译阶段,ngIf包含了你的指令,该指令在那时编译它,但元素在链接阶段之前还没有在 DOM 中 -
@NewDev 属性位是其中的一部分,但我的实际目标是通过移动自定义指令元素来修改模板,使其成为父元素的兄弟元素,与子元素相对。关于您对 transclude 的评论:我的印象是 transclude 函数在 compile 函数之后运行。你确定它之前运行过?
-
@ductiletoaster 是一个更大的坚持者,jqLite 是 jQuery 的一个分支版本,具有自己的特性......所以除非你包含它,否则你没有使用 jQuery。 :-)
-
@ShaunScovil,您能否在问题中附加一个用例 - 这可能会有所帮助,因为您尝试做的事情似乎有些不自然。为指令提供被嵌入内容的克隆的 transclude 函数在链接时运行(因此,在编译之后),但内容的嵌入本身(即内容的提取和编译)发生在 compile-时间。
标签: javascript angularjs angularjs-directive angularjs-compile jqlite