使用基于其他DOM元素的ng-style变量

时间:2016-04-25 20:51:35

标签: javascript jquery css angularjs ng-style

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

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

        <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,但我在别处使用它没有问题,但基本上我只是想根据第一个表的行高来对齐每个表中行的高度(。表格1)。所以问题是,如何获取table1中行的高度值并使用angular将其作为table2中同一行的高度应用?

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:0)

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

请参阅我所做的JSFiddle示例:http://jsfiddle.net/bpxv80nj/

HTML:

newname/null

JS:

<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>