0

I have a directive which needs to access the width of an element inside of it. The problem I am having is that the width contains dynamic text which is compiled by angular and it seems to take at least 35 milliseconds for angular directive to actually compile inside link function. As a result I've added a setTimeout-to-zero function, but this feels really dirty. Am I missing something or is this just an angularjs bug? Here is the code.

Javascript:

angular.module('myApp', [])
    .directive('myDir', MyDirective);

function MyDirective() {
    return {
        restrict: 'E',
        scope: {
            mytext : '@'
        },
        template: '<span>{{mytext}}</span>',
        link: function(scope, elem, attr) {
            console.log(Date.now(), elem.text());
            setTimeout(function() {
                console.log(Date.now(), elem.text());
            }, 0);
        }
    }
}

HTML:

<div ng-app="myApp">
    <my-dir mytext="Hello"></my-dir>
</div>

And here is an example of the results from console:

1438529990502 "{{mytext}}"
1438529990523 "Hello"

You can demo here: https://jsfiddle.net/38m6hxk6/15/

Erick R Soto
  • 1,331
  • 9
  • 6
  • angular think 50ms is instant - http://stackoverflow.com/questions/9682092/databinding-in-angularjs – YOU Aug 02 '15 at 15:58
  • use `$timeout` with no time set, or use `$compile` yourself. Can't expect everything to be synchronous ... even repaint of DOm takes time – charlietfl Aug 02 '15 at 16:13

1 Answers1

1

You're right in that you need a timeout, you should use angulars $timeout though. It will wait for angular to complete the latest digest cycle. You can read about it on the docs.

https://docs.angularjs.org/api/ng/service/$timeout

Mathew Berg
  • 28,625
  • 11
  • 69
  • 90