Search code examples
javascriptjquerycssangularjsng-style

Use variable in ng-style based on other DOM element


I have two tables (.table1 and .table2) that sit side by side in separate DIVs on a page and regardless of content I want the second table rows to match the height of the first table rows so that they align perfectly. The first table is built using ng-repeat based on values from a database, so can height can vary - either way the equivalent row in the second table should always match.

I've been trying many different ideas, but was thinking that using a jQuery selector in the ng-style for table2 rows may work (see below) but it doesn't;

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

or

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

obviously not working, but if I replace the jQuery selector with a specific value it styles the row as expected;

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

I'm not fussed about using jQuery, but am using it elsewhere so no issues with that, but basically I just want to align height of the rows in each table based on the row height of the first table (.table1). So the question is, how do I get the height value of a row in table1 and apply it as the height of the same row in table2 using angular?


Solution

  • You could use jQuery to fetch the size of the other table but you need to go via the controller.

    I have it fetching the updated height on click of the green box, but you could equally do it on the render of the table.

    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>