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

Javascript 使用$compile创建指令,并立即获取DOM属性,javascript,angularjs,dom,Javascript,Angularjs,Dom,我创建了一个angularjs指令,该指令动态创建多个指令,并将它们放在DOM上的特定div中。 在创建每个指令之后,我需要计算包装div的大小,以进行额外的操作。我看到,在调用$compile()动态创建指令之后,它们还不在DOM中 在调用$compile()之后,如何强制angularjs立即更新DOM,以便之后可以使用DOM 下面是一个示例,试图说明我在做什么: // This is my wrapping directive angular.module('myModule').dire

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

在调用
$compile()
之后,如何强制angularjs立即更新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...
        }
    };
});
//这是我的包装指令
角度.module('myModule')。指令('wrapper',函数($compile){
返回{
限制:“A”,
模板:“”,
范围:{
//这里的范围是对象列表,这些对象是要创建的内部指令的模型
内部模型:'='
},
链接:函数(范围、元素、属性){

对于(var i=0;i,简单的答案是在下一个摘要周期中运行您的代码,这将确保您的元素已在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
    }
链接:函数(范围、元素、属性){

对于(var i=0;我为什么不在
compile
link
中添加您想要的内容,然后在链接中检查您的clientHeight?我不知道将其添加到
compile
是什么意思?实际的用例是,在添加内部指令时,我需要知道它们的clientHeight。(我将更新示例以更清楚地显示)就像您有directive.link函数一样,您也有directive.compile函数