2

I have two html elements and I want to bind the size of one to the size of another like:

<div id="elem1"> </div>

<div style="height:some binding expression to the height of elem1; 
     width:another binding expression to width of elem1"></div>

Is this even possible? The binding only needs to happen once.

2
  • Do they always need to be equal(page resize, ect) or simply on page load ? Commented Jul 25, 2016 at 13:48
  • @AndrewDonovan just on page load Commented Jul 25, 2016 at 13:53

2 Answers 2

3

Use the ng-style directive on the second element. You can set styling on the elements via object form, and is automatically updated when the value changes.

On page load, calculate the height of elem1 and set it to a scope variable, lets say:

$scope.elemStyle = {
    height: calculated_elem1_height
}

Then your second element <div ng-style="elemStyle"></div>

Every time you update the variable $scope.elemStyle, the DOM will be updated.

EDIT

calculated_elem1_height needs to be a string, Eg: "100px"

Sign up to request clarification or add additional context in comments.

Comments

0

$timeout will ensure the DOM is loaded

var test = angular.module("myApp", []);
test.directive('equalTo', function($timeout) {
  return function(scope, element, attrs) {
    $timeout(function() {
      var e = angular.element(document.querySelector(attrs['element']))[0]
      element.css("width", e.offsetWidth + "px") 
      element.css("height", e.offsetHeight + "px")
    }, 0);
  };

});
#elem1 {
  background: red;
  display: inline-block;
  width: 200px;
  height: 150px;
}
#elem2 {
  background: black;
  display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
  <div id="elem1"> </div>
  <div id="elem2" equal-to element="#elem1"></div>
</body>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.