0

So I want to create an element in angular and append it to DOM :

   //in my directive I've created an element as bellow :

  el = $compile('<span>Hello dynamically</span>')($scope);

  // and then I appended it to my DOM like this : 

  myDomElement.append(el);

So far so good , no errors no nothing .

All I'm looking for is to how to get the width of this el that I've created in my directive ?

Normally when I want to get width of an element I'll get the offsetWidth of that element ,

I'm looking for something like this :

   el = $compile('<span>Hello dynamically</span>')($scope);

   var width  = el.offsetWidth   ; // I want the width here !!
   console.log(width); // will log 0 !!!!!!
   console.log(el); // will show an Object that has a **offsetWidth:134** property !!!!!!!

   myDomElement.append(el);

But when I log this , I always get 0 , it's weird because when I look at my developer tools in chrome I can see that offsetWidth is not 0 !

1 Answer 1

1

Do this :

 el = $compile('<span>Hello dynamically</span>')($scope);
 myDomElement.append(el);
 var width  = el.offsetWidth   ; // I want the width here !!
 console.log(width); 

Means first append the element to DOM , then get it's width

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks mate , It works , can you explain why is that ?
An element does not have a width or a height if it's not in the DOM.

Your Answer

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