0

I have this directive:

angular.module('exampleApp').directive('exampleDirective', ['$document', '$window', function($document, $window) {
    return {
        restrict: 'E',
        scope: false,
        template: '<div class="foo"></div>',
        link: function($scope, $element, $attrs) {
            var targetElement = angular.element(document.querySelector($attrs['targetSelector']));
            console.log(targetElement.css('height'));
        }
   }
]);

Which works fine with this html:

 <div id="div1" style="height: 100px">A div</div>
 <example-directive target-selector="#div1" />

Because in the console I see: "100px" printed out

But with this html:

 <style>
      .div-example {
          height: 100px;
      }
 </style>

 <div id="div2" class="div-example">A div</div>
 <example-directive target-selector="#div2" />

Which is basically the same but without inline-style, the directive is simply not working. The console is printing: "" (empty string).

How do I solve this?
I tried scope: true but it didn't work either.
Is targetElement.css('height') only good for inline style?

sports
  • 7,851
  • 14
  • 72
  • 129
  • id="#div2" should be id="div2" – YOU Apr 14 '15 at 15:38
  • yeah that was a typo when writing the question, sorry... the real code doesn't have that typo. I've fixed the code in the question. – sports Apr 14 '15 at 15:40
  • 1
    jqlite - css - Only retrieves inline-styles, does not call getComputedStyle() - https://docs.angularjs.org/api/ng/function/angular.element#css() – YOU Apr 14 '15 at 15:55
  • fyi - [clientHeight or offsetHeight](http://stackoverflow.com/questions/15615552/get-div-height-with-plain-javascript) is way to go - http://plnkr.co/edit/HU2l3gkMeotndxVCEHON?p=preview – YOU Apr 14 '15 at 16:00

1 Answers1

1

When you do .css('height'), jQuery can tell you only the values set in the element's style property or attribute.

If you want to know the actual height of an element, try with

targetElement[0].clientHeight

Or with jQuery:

targetElement.height()

See the difference explained a bit better here: https://api.jquery.com/height/

Victor
  • 9,210
  • 3
  • 26
  • 39
  • but i'm not even using jquery... this is the angular's own jqLite (i think that is how its called) – sports Apr 14 '15 at 15:42
  • also `targetElement.clientHeight` is giving me undefined – sports Apr 14 '15 at 15:44
  • Sorry, should have specified it better. your `targetElement` is a jqlite object and clientHeight is a property of the actual DOM element. use `.height()` or do `.get(0).clientHeight` – Victor Apr 14 '15 at 15:46
  • Marked as accepted although I ended up using this: `window.getComputedStyle(targetElement[0], null).getPropertyValue("height")`, because I needed the computed height, not the `clientHeight` nor the `offsetHeight` – sports Apr 14 '15 at 16:21