使用$compile创建指令,并立即获得DOM属性

using $compile to create directive, and immediately get DOM properties

本文关键字:DOM 属性 compile 创建 指令 使用      更新时间:2023-09-26

我创建了一个angularjs指令,它可以动态地创建多个指令,并将它们放在DOM的特定div中。
在创建每个指令之后,我需要计算包装div的大小,以进行额外的操作。我看到在调用$compile()动态创建指令后,它们还没有在DOM中。

我怎么能强迫angularjs在调用$compile()后立即更新DOM,以便我可以在那之后玩DOM ?

这里有一个例子来展示我在做什么:

// This is my wrapping directive
angular.module('myModule').directive('wrapper', function($compile) {
    return {
        restrict: 'A',
        template: '<div></div>',
        scope: {
            // the scope here is a list of objects that are the models for the inner directives to be created
            innerModels: '='
        },
        link: function(scope, element, attrs) {
            for (var i=0; i<innerModels.length; i++) {
                var innerDirective = $compile('<inner-directive ng-model="innerModels['+i+']"></inner-directive>')(scope);
                element.append(innerDirective);
                // here I want to get the client size of the 'div' i created
                var divHeight = element[0].clientHeight;
                // divHeight == 0
                // but after the page loads
                // if i open the developer console when the page is finished loading, then the div does have a clientHeight value
            }
        }
    };
});
angular.module('myModule').directive('innerDirective', function() {
    return {
        restrict: 'E',
        template: '<span ng-bind-template="{{somethingFromModel}}"></span>',
        scope: {
            ngModel: '='
        },
        link: function(scope, element, attrs) {
            // some logic...
        }
    };
});

注意:我这里没有使用jQuery(所以如果答案不包括jQuery解决方案我会很高兴)

简单的答案是在下一个摘要循环中运行您的代码,这将确保您的元素已绘制在DOM上,您可以使用$timeout

    link: function(scope, element, attrs) {
        for (var i=0; i<innerModels.length; i++) {
            var innerDirective = $compile('<inner-directive ng-model="innerModels['+i+']"></inner-directive>')(scope);
            element.append(innerDirective);
        }
        // here I want to get the client size of the 'div' i created
        $timeout(function(){
           //here you will get update height.
           //play with rendered DOM here
        })
        // but after the page loads
        // if i open the developer console, then the div does have a clientHeight value
    }