简体   繁体   中英

angularjs directive slow dom manipulation

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/

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM