我有以下情况:
<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);
}
}
}
};
});
说明问题的图片:
答案 0 :(得分:2)
尝试删除float: left
样式并改为应用这些样式:
.parent {
display: table;
}
.parent > * {
display: table-cell;
}
答案 1 :(得分:1)
如评论所示,您可以使用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);
}
};
});