Sudhir
Sudhir

Reputation: 149

Angularjs - How to have same height for the child divs when one child div's size is increased dynamically with ng-repeat

I have created a parent div. In this parent div, I have added 2 child divs. First child div contains list, which is created using ng-repeat. The first div also has border around it. This first div grows and shrinks based on the list of items. I want the second div to have the same height as the first div so that both the borders are aligned in the parent (i.e., with same height). I know how to do this using jquery. However, I would like to know simpler approaches to this problem either using CSS or Angularjs. Thanks for helping me.

Example of the issue in Plunker : http://plnkr.co/edit/yGI1cJ3y594O89bEZAIH?p=info

<script data-require="angular.js@*" data-semver="1.4.0-beta.4" src="https://code.angularjs.org/1.4.0-beta.4/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>

Issue: Same height for both child divs

<div class="row" ng-controller="mainCtrl">
  <div class="col-md-6" style="background-color:lightblue; border-style: solid; border-width:1px;">
    <div class="col-md-12" ng-repeat="item in items" >
      <div>{{item}}</div>
    </div>
  </div>
  <div class="col-md-6" style="background-color:lightred;border-style: solid; border-width:1px;">
    <br />
    Enter new item to see in the list:
    <br />
    <input type="text" ng-model="newItem" /> 
    <input type="button" ng-click="addItem()" value="Add" />
  </div>
</div>


<script>
var app = angular.module("mainApp", []);
app.controller("mainCtrl", function ($scope) {
  $scope.items = [1, 2, 3, 4, 5, 6, ];
  $scope.newItem = "";

  $scope.addItem = function() {
    $scope.items.push($scope.newItem);
    $scope.newItem = "";
  }
});

</script>

Upvotes: 0

Views: 4659

Answers (1)

Bricktop
Bricktop

Reputation: 1549

This question seems to be a duplicate of this question which I answered here.

The solution is to create a Directive that watches the height changes on your div:

app.directive('master',function () { //declaration; identifier master
    function link(scope, element, attrs) { //scope we are in, element we are bound to, attrs of that element
      scope.$watch(function(){ //watch any changes to our element
        scope.style = { //scope variable style, shared with our controller
            height:element[0].offsetHeight+'px', //set the height in style to our elements height
            width:element[0].offsetWidth+'px' //same with width
          };
      });
    }
      return {
        restrict: 'AE', //describes how we can assign an element to our directive in this case like <div master></div
        link: link // the function to link to our element
      };
});

You can read more about it in my answer I linked above.

Upvotes: 3

Related Questions