Angular Set动态高度为其父div的元素

时间:2015-05-30 11:02:25

标签: javascript css angularjs

我有以下情况:

 <div class="parent" style="height:100%">
        <div class="left" style="float:left" dynamic-height element-id="{{$index}}">
        </div>
        <div class="right" style="float:left">
            <div>Element 1</div>
            <div>Element 2</div>
    </div>
    </div>

我正在尝试左侧元素与.right或.parent的高度相同,我试图为此添加指令,但没有太大成功,任何人都有更好的想法?

指令:

.directive('dynamicHeight', function() {
    return {
        compile: function compile(tElement, tAttrs, transclude) {
            return {
                post: function postLink(scope, elem, attrs) {
                    var element = "#discussion-element-"+ attrs.elementId;
                    var myEl = angular.element( document.querySelector( element) );
                    var height = myEl[0].offsetHeight;
                    element.height(height);
                }
            }
        }
    };
});

说明问题的图片:

enter image description here

2 个答案:

答案 0 :(得分:2)

尝试删除float: left样式并改为应用这些样式:

.parent {
    display: table;
}

.parent > * {
    display: table-cell;
}

答案 1 :(得分:1)

最好在css中执行此操作,

如评论所示,您可以使用css来获取它。 (例如https://css-tricks.com/fluid-width-equal-height-columns/

如果你还想要角度

您可以在指令范围内添加$watch,以便在父元素的width & height发生更改时获得回调。从那里你可以改变元素高度

<强> HTML

<div class="container demo">
    <div ng-controller="MyCtrl">
        <div>
            <button class="btn btn-primary" ng-click="isLarger = !isLarger">toggle parent size</button>
        </div>
        <hr>
        <div class="parent" ng-class="{'larger':isLarger}">
            <div class="child" dynamic-height>{{message}}</div>
        </div>
    </div>
</div>

<强> JS

var app = angular.module('myApp', []);

app.controller('MyCtrl', function ($scope) {
    $scope.message = 'hello';
});

app.directive('dynamicHeight', function () {
    return {
        restrict: 'A',
        link: function (scope, elm, attrs) {
            var parent = elm.parent();

            scope.$watch(function () {
                return {
                    height: parent.prop('offsetHeight'),
                    width: parent.prop('offsetWidth')
                };
            }, function (size) {

                // Here you have `size = {height: ... , width: ... }`
                // you can manipulate the element with this data. for example:

                // elm.css('min-width', size.width + 'px');
                // elm.css('min-height', size.height + 'px');

                // -- note that this will make the responsiveness of the ui a bit more challanging 
            }, true);
        }
    };
});

http://jsfiddle.net/f62ccw5a/