48

I'm getting familiar with AngularJS. I'm trying to be as 'pure' as I can. For that reason, I'm trying to avoid including jQuery. However, I'm having a challenge getting an HTML element's height. Currently, I'm trying the following:

angular.module('myModule', [])
  .directive('myDirective', function() {
    return {
        restrict: 'A',
        link: function(scope, element) {
            console.log(element.css('height'));
        }
    };
  })
;

However, when this code gets executed, an empty line gets written to the console. I'm trying to display the height of the element. Is there a way to do this in AngularJS without using jQuery?

Thank you!

user3284007
  • 1,697
  • 7
  • 27
  • 43

2 Answers2

61

It appears this is working correctly and gives the same result if you use:

element.style.height

Since no inline style or CSS height is set on the element a blank line is shown. Instead of relying on the style you can get the HTML elements height directly.

console.log(element[0].offsetHeight);

http://plnkr.co/edit/03YWwjBjYpid4fVmDxlM?p=preview

How do I retrieve an HTML element's actual width and height?

Community
  • 1
  • 1
shaunhusain
  • 19,630
  • 4
  • 38
  • 51
  • 4
    This worked for me! I was trying to remove jQuery from my application, which was using `angular.element('#header').height()`. You can do the same thing with `angular.element(document.querySelector('#header'))[0].offsetHeight`. Thanks! – Jake McGuire May 20 '14 at 01:27
  • 2
    You may or may not care about this, but `document.getElementById` would be better in terms of performance than querySelector for an ID. – Gary Justin Jun 11 '14 at 18:28
  • I was unable to reproduce it to show. Issue I'm having is that element rendered with ng-repeat and same, but static element have different height. Can the reason be diff. load time? What I mean is, that one needs to get content from Javascript to set DOM and the other has it in plain sight. Is there some workaround for that if that is the case? – Eugene Jan 06 '15 at 08:44
23

The small wrapper around element provided by angular allows you to ask for properties, so:

element.prop('offsetHeight');

Will just work fine, see: http://plnkr.co/edit/pFHySDo7hjEcMKCqGuiV?p=preview

IxDay
  • 3,667
  • 2
  • 22
  • 27