iamsar
iamsar

Reputation: 1130

AngularJS: how to access clientWidth (vanilla JS methods) on the element

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

Upvotes: 2

Views: 3983

Answers (1)

iamsar
iamsar

Reputation: 1130

yes.

var totalWidth, totalHeight;
scope.$watch(element, function () {
  totalWidth = element[0].clientWidth;
  totalHeight = element[0].clientHeight;
  console.log(totalWidth);         // returns 100
}

Upvotes: 4

Related Questions