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

时间:2015-08-23 08:45:25

标签: javascript angularjs dom

我创建了一个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...
        }
    };
});

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

1 个答案:

答案 0 :(得分:2)

简单的答案是在下一个摘要周期中运行您的代码,这将确保您的元素已经在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
    }