Francisc
Francisc

Reputation: 80415

Get the bounding rect for an element outside of a directive

Inside a directive I want to get the result of getBoundingClientRect() for a DOM element that is no where near the element of the directive.

How should I go about this? Service that just returns that object? Is it OK to have DOM logic in a service?

Upvotes: 0

Views: 1186

Answers (1)

Joel Skrepnek
Joel Skrepnek

Reputation: 1661

I'd suggest passing the id of the element the directive needs to interact with as an attribute to the directive. Then use the document object to get a handle to that element.

See: http://jsfiddle.net/afX63/6/.

You'll obviously need to work directly with the raw DOM element to access the information you're interested in.

Your markup:

<my-directive handle-id="thatOne"/>

<div id="thatOne">Your directive can find this element easily now</div>

You directive:

app.directive('myDirective', function () {
    return {
        link: function (scope, elem, attrs) {
            var theHandle = angular.element(document.getElementById(attrs.handleId));
            theHandle.text('Changed it');
        }
    }
});

Upvotes: 1

Related Questions