如何在我的场景中获取父元素高度?

时间:2015-10-15 00:50:02

标签: javascript html angularjs

我试图在我的指令中获取父元素的高度。

我有类似

的东西
(function(window, angular) {
    var app = angular.module('myApp');
    app.directive('testElem', [
        function() {
            return {
                restrict: 'A',
                template:'<a class="button"></a>',
                link: function(scope, element) {                        
                    var height = angular.element(element).parent().height();
                    console.log(height); 
                    //the height is 0 because not all item.description are   
                    //rendered
                }
            };
        }
    ]);
})(window, angular);

HTML

<div id="container">
    <div ng-repeat="item in items">
        {{item.description}}
    </div>
    <a test-elem href="#"></a>
</div>

我想在我的页面中呈现所有#container之后获得{{item.description}}的高度。一旦doms完成没有item.description,我当前的代码将获得它的父亲的高度。

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

您应该能够在页面上呈现项目后使用$timeout来运行:

(function(window, angular) {
    var app = angular.module('myApp');
    app.directive('testElem', [
        function($timeout) {
            return {
                restrict: 'A',
                template:'<a class="button"></a>',
                link: function(scope, element) {   
                    $timeout(function () {
                        var height = angular.element(element).parent().height();
                        console.log(height); //height should be accurate
                    });
                }
            };
        }
    ]);
})(window, angular);

$ timeout返回一个promise,当延迟过去并执行提供的超时功能时,该promise将被解析。 https://docs.angularjs.org/api/ng/service/$timeout

答案 1 :(得分:1)

使用ng-repeat指令异步编译指令中的

。您可以设置承诺并解决它。

typedef struct complex complex;
typedef struct complex_set complex_set;

struct complex { double a; double b; };
struct complex_set {
    int num_points_in_set;
    complex *points; // an array of struct complex
};

struct complex_set *alloc_set(complex c_arr[], int size) {
    complex_set *set = (complex_set *) malloc(sizeof(complex_set));
    set->num_points_in_set = size;
    // i think i may even just use the pointer c_arr as '*points'
    // however, i want to make sure malloc was called
    set->points = (complex *) malloc(size*sizeof(complex));
    for (int i=0; i<size; i++) {
        set->points[i] = c_arr[i];
    }
    return set;
}

void free_set(complex_set *set) {
    complex *current = set->points;
    complex *next = NULL;
    int iterations = set->num_points_in_set;
    for(int i=0; i<iterations; i++) {
        next = current + 1;
        // i get the error here, in the second iteration:
        free(current);
        current = next;
    }
    free(set);
    set = NULL;
}

这是一个工作样本: JsFiddle