我正在使用 vanilla AngularJS v1.4.5(无 jQuery),并希望我的自定义指令在编译时向其祖父元素添加一个属性。
在编译函数中,我可以使用两次获取祖父元素的方法和添加我的属性的方法来parent()
实现这一点。但是,如果父元素具有ngIf指令,则祖父元素不会获得该属性。element
attr()
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
,因为这是在编译阶段发生的,在作用域被链接到任何元素之前。 - 我的 compile 函数应该在 of 之前运行
ngIf
,它的优先级为600
(并且没有 compile function)。 ngIf
完全删除并重新创建 DOM 中的元素(连同其子元素),但这不应影响祖父元素或更改其属性。
如果父元素具有指令,谁能向我解释为什么我不能向指令的祖父元素添加属性ngIf
?