您可以將您的函數從鏈接函數中分離出來,以便在窗口調整大小並通過傳遞由jQuery包裝的角元素進行加載時重用它。
另外:
- 在原來的提琴的angularjs初始化
ng-app="App"
丟失。這導致您的應用程序無法運行。
- 聲明指令時,使用camelCase語法,
caclulateRow
。但是,在html上應用時,必須使用XML,如語法(dash-delimited);即caclulate-row
。
var app = angular.module('App', []);
app.directive("caclulateRow", [function() {
function tableAdjustedHeight(el) {
var firstColHeight = el.find('td:nth-child(1)').outerHeight();
var secondColHeight = el.find('td:nth-child(2)').outerHeight();
var thirdColHeight = el.find('td:nth-child(3)').outerHeight();
var fourthColHeight = el.find('td:nth-child(4)').outerHeight();
el.find('td:nth-child(2)').css('top', firstColHeight);
el.find('td:nth-child(4)').css('top', thirdColHeight);
var leftColHeight = firstColHeight + secondColHeight;
var rightColHeight = thirdColHeight + fourthColHeight;
var colHeightArray = [leftColHeight, rightColHeight];
var largeHeight = Math.max.apply(null, colHeightArray);
el.height(largeHeight);
}
return {
restrict: "A",
scope: {
},
link: function (scope, element, attr) {
var el = $(element);
if ($(window).width() < 992) {
tableAdjustedHeight(el);
}
$(window).resize(function() {
tableAdjustedHeight(el);
});
}
};
}]);
.table td {
width: 25%;
}
@media (max-width: 991px) {
.table tr {
position: relative;
}
.table td {
display: inline-block;
width: 50%;
}
.table td:nth-child(2){
position: absolute;
left: 0;
}
.table td:nth-child(4){
position: absolute;
right: 0;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<table class="table" ng-app="App">
<tr class="main-row" caclulate-row>
<td>Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text</td>
<td>Text Text Text Text</td>
<td>Text Text Text Text Text Text</td>
<td>Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text</td>
</tr>
</table>
非常感謝您! – user1896653