Squrler
Squrler

Reputation: 3514

Angular: Selecting elements from DOM

I'm using an ng-repeat to create items. I would like to determine the height of each element that is created by using a function.

I know how to pass the index of the element that is created by ng-repeat to the function that should determine the height, but I'm getting stuck in actually selecting that item.

This is what I'm using now:

   $scope.getItemHeight = function(index) { // index is index of element in ng-repeat
    var itemHeight = angular.element('li').eq('+index+').offsetHeight;
    return itemHeight;
   };

But that doesn't work due to error: Error: [jqLite:nosel] Looking up elements via selectors is not supported by jqLite!

I also tried:

   $scope.getItemHeight = function(index) {
    var itemHeight = document.querySelectorAll('ul:nth-child('+index+')');
    return itemHeight;
   };

This returns an element with length 0 so the selector doesn't work.

What am I missing here?

Codepen here: http://codepen.io/squrler/pen/LxsfE?editors=101


EDIT: What I want is not possible at this time. More information here: https://github.com/driftyco/ionic/issues/1691

Upvotes: 0

Views: 2488

Answers (1)

Adam Matthews
Adam Matthews

Reputation: 201

Edit: After looking at this further it seems a bit more complicated. The directive that is firing the repeater needs to run in order for the lis to be rendered, as the li is rendered (assuming you move this to a directive) it triggers the directive to get its height, but the li and it's corresponding data are not yet fully rendered and thus have no height. If you wait for the rendering using timeout, the repeater will just continue rendering without valid height data while the timeout waits. So it seems you have a bit of a conundrum. You might try using http://binarymuse.github.io/ngInfiniteScroll/ or something of the like.

This should be put in a directive which will give you easy access to the li as it is rendered.

Something like:

.directive('getHeight', ['$filter', function ($filter) {
    'use strict';

    return {
        restrict: 'A',
        scope: true,
        link: function (scope, element, attrs) {
            var li = element[0];
            var height = li.offsetHeight;
            console.log('Height': height)
        }
    };
}]);

Not sure what you're looking to do with the height once you have it...

Otherwise you can just go:

var ul=document.getElementsByTagName('ul')[0];
var li=ul.getElementsByTagName('li')[index];
var height=li.offsetHeight;

Upvotes: 1

Related Questions