Reputation: 3532
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.
Upvotes: 2
Views: 68
Reputation: 5574
$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>
Upvotes: 0
Reputation: 552
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"
Upvotes: 3