'Access parent element(body) in directive link function

Given a HTML structure similar to this:

<body>
    <div id="one" my-directive></div>
    <div>
        <div id="two" my-directive></div>
    </div>
</body>

When I try to access the parent element of two It works and the log returns the parent div, but when the parent is the body, as in one case, it doesn't work and returns an empty set.

app.directive 'myDirective', ->
    (scope,iElement,iAttrs) ->
        console.log iElement.parent()

EDIT: My guess for this problem is that my app's body is rendered on client side and appended to the body element on module's run method. The html is inserted with $('body').html($compile(body.render())($rootScope)); and I suppose the directive is called within the $compile function before the contents are inserted in the body. Can I work around this problem?



Solution 1:[1]

Indeed you understood your problem correctly: $compile will trigger the template compilation and linking phases on your element, so it has no parent while doing so.

The easy way to fix that is to first append your HTML to the body, and then compile it.

var html = body.render();
$('body').html(html);
$compile(angular.element(body))($rootScope);

Or if you don't want to compile the whole body but just the new element:

var elem = $( body.render() ).appendTo($('body'));
$compile(elem)($rootScope);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 floribon