I'm using vanilla AngularJS v1.4.5 (no jQuery) and would like my custom directive to add an attribute to its grandparent element at compile time.
In the compile function, I can achieve this using the parent()
method of element
twice to get the grandparent element, and the attr()
method to add my attribute. However, if the parent element has the ngIf directive, the grandparent element does not get the attribute.
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');
}
}
Here's what I know:
- If
ngIf
is not used on the parent element, the attribute gets added to the grandparent. - The problem should not be related to
scope
, since this is taking place during the compile phase, before scope has been linked to any elements. - My compile function should be running before that of
ngIf
, which has a priority of600
(and doesn't have a compile function). ngIf
completely removes and recreates the element in the DOM (along with its child elements), but that should not affect the grandparent element or change it's attributes.
Can anyone explain to me why I cannot add an attribute to my directive's grandparent element if the parent element has the ngIf
directive?