2

Really, I think this is more a question of timing... Using the console, if I log "element" (from within a directive) I can clearly see the element object (at index [0]) and all the normal JS methods: clientWidth, offsetWidth, innerHTML, etc. It will also show the correct value for clientWidth. The problem is when I try to access element[0].clientWidth, that returns a value of 0. So it appears that it's trying to grab the value before the DOM has created the element even though it's being accessed from within the linking function.

Can I use $defer or $watch to wait for the value before using in a variable?

For usage/reference:

angular.module('angularCharts').directive('acChart', ['$templateCache', '$compile','$window', function ($templateCache, $compile, $window) {
function link(scope, element, attrs) {
  var totalWidth = element[0].clientWidth,
     totalHeight = element[0].clientHeight;

  console.log(element);                   // returns object[0].clientWidth = 100
  console.log(element[0];                 // returns DOM element
  console.log(element[0].clientWidth)     // returns 0
}]);

Source: https://github.com/chinmaymk/angular-charts/blob/master/dist/angular-charts.js

1 Answer 1

4

yes.

var totalWidth, totalHeight;
scope.$watch(element, function () {
  totalWidth = element[0].clientWidth;
  totalHeight = element[0].clientHeight;
  console.log(totalWidth);         // returns 100
}
Sign up to request clarification or add additional context in comments.

3 Comments

didn't expect to answer that so easily on my own :p Figured I'd leave it here in case anyone finds it helpful or if someone has a different suggestion
Can you expand a bit on how you used this? I'm hitting a very similar issue and I can't see how to use your solution.
@andrewdotnich I don't recall the specifics except the directive was likely placed on a DIV that relied on the knowing the correct size. Within the linking function, declare your variable with no value. Element will initialize with 0 value because the page hasn't rendered yet. So use a $watch or $watchCollection on the element. When the page renders the properties of the element will update which can then be assigned to the variable. You have to access the element as an array to expose normal javascript methods. Element by itself restricts you to jQuery Lite

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.