0

我有两个表(.table1 和 .table2)并排放置在页面上的单独 DIV 中,并且无论内容如何,​​我都希望第二个表行与第一个表行的高度匹配,以便它们完美对齐。第一个表是使用 ng-repeat 基于数据库中的值构建的,因此高度可以变化 - 无论哪种方式,第二个表中的等效行都应该始终匹配。

我一直在尝试许多不同的想法,但我认为在 ng 样式中为 table2 行使用 jQuery 选择器可能有效(见下文),但它没有;

        <tr ng-style="{'height': $('.table1 tr').eq('$index').height()+'px' }"></tr>

或者

        <tr ng-style="{'height': $('.table1 tr:nth-child($index).height()+'px' }"><tr>

显然不起作用,但如果我用特定值替换 jQuery 选择器,它会按预期设置行的样式;

        <tr ng-style="{'height': 50+'px'}></tr>

我对使用 jQuery 并不在意,而是在其他地方使用它,所以没有问题,但基本上我只想根据第一个表 (.table1) 的行高对齐每个表中行的高度。所以问题是,如何获取 table1 中一行的高度值,并使用角度将其应用为 table2 中同一行的高度?

4

2 回答 2

0

您可以使用 jQuery 来获取另一个表的大小,但您需要通过控制器。

我让它在点击绿色框时获取更新的高度,但您同样可以在表格的渲染上执行此操作。

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

myApp.controller('MainController', ['$scope', function($scope) {
  $scope.person = {
    firstName: 'Mike',
    lastName: 'Smyth'
  };
  $scope.myStyle = {};
  $scope.findStyle = function(selector){
    $scope.myStyle = {'height': ($(selector).height() + 'px')};
  }
}]);
.person{
  background: green;
  width: 50%;
  float: left;
}
.bigDiv{
  background: blue;
  width: 50%;
  float: left;
  height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html>
<body ng-app="myApp">
    <div ng-controller="MainController">
      <div class="person" ng-style="myStyle" ng-click="findStyle('.bigDiv')">{{person.firstName}} {{person.lastName }}</div>
      <div class="bigDiv"></div>
    </div>
</body>
</html>

于 2016-04-25T21:12:40.803 回答
0

您的代码将无法工作,因为当您尝试获取行高并将其分配给其他表中的行高时模板未完全呈现。您需要在控制器中添加一些观察者,它将跟踪模板何时加载,并在下一次迭代循环遍历表 1 行并将它们的高度分配给表 2 行。

请参阅我制作的这个 JSFiddle 示例:http: //jsfiddle.net/bpxv80nj/

HTML:

<div ng-controller="MyCtrl">
   <div class="col">
      <table class="table1">
         <tr data-ng-repeat="(i, row) in table1">
            <td>{{i + 1}}</td>
            <td data-ng-bind="row.text"></td>
         </tr>
      </table>
   </div>
   <div class="col">
      <table class="table2">
         <tr data-ng-repeat="(i, row) in table2">
            <td>{{i + 1}}</td>
            <td data-ng-bind="row.text"></td>
         </tr>
      </table>
   </div>
</div>

JS:

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

function MyCtrl($scope, $timeout) {

    $scope.$watch('$viewContentLoaded', function() {
        $timeout(function() {
            $('.table1 tr').each(function() {
                $('.table2 tr').height($(this).height());
            });
        });
    });

    $scope.table1 = [{
        text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sagittis sem ut pharetra sagittis. Nam luctus suscipit augue at suscipit. Maecenas quis justo mauris.'
    }];

    $scope.table2 = [{
        text: 'Lorem ipsum dolor sit amet'
    }];
}
于 2016-04-25T21:36:25.517 回答