Tucker
Tucker

Reputation: 7362

angular - ui-router - directive - get offset/position of directive

I've had this issue with many projects using angular and ui-router.

I have a directive, and I simply want to get its size/position or the size/position of its containing element. In my directive, which is rendered in a ui-router view, I've attached a controller, and when I try to get the size, however, it's always zero.

element.position() -> Object {top: 0, left: 0}
element.offset() -> Object {top: 0, left: 0}

in my directive I have this:

templateUrl: 'some-html-file',
link: function (scope, elem, attrs, someController) {
    someController.init(elem);
}

in someController

this.init = function (element) {
     $scope.element = element;
     console.log($scope.element.position());
     console.log($scope.element.offset());
}

Im not sure how I can get the position and size of my directive. Are there any ideas? is this related to ui-router or maybe this is related to angular using a directive? I'm guessing its a timeing issue - trying to get info on the dom before angular is finished with the dom? any help appreciated!

Upvotes: 0

Views: 187

Answers (1)

Estus Flask
Estus Flask

Reputation: 222379

Such style-related routines need to be postponed. Some things didn't happen when link ran (first of all, child's link precedes its parent). And usually you have to do

link: function (scope, elem, attrs, someController) {
    $timeout(function () {
        someController.init(elem);
    });
}

Likewise, other directives will postpone some things to the next digest, and occasionally you need $timeout with non-zero delay to make it work.

Upvotes: 1

Related Questions