Reputation: 167
i am new to angular :-) i simply want to set dimensions of one div to another, any help appreciated.
<div class="front">
<img ng-src="{[galery.pages[0].thumbnailUrl]}" >
</div>
<div ng-style="galery.pages[1] ? '' : setBackDimensions(); " ></div>
and in the controller i have added:
$scope.setBackDimensions = function() {
var imgHeight = $(".front").height;
var imgWidth = $(".front").width;
return {
'width': imgWidth + 'px';
'height': imgHeight + 'px';
}
};
and it is returning width and height, but they are not applied
Upvotes: 10
Views: 13526
Reputation: 43
Here is an example for applying other elements width to current element.
Width of the element which has the class name "container" will apply to div using flexibleCss angular js directive
<div flexible-width widthof="container">
</div>
myApp.directive('flexibleWidth', function(){
return function(scope, element, attr) {
var className = attr.widthof;
var classWidth = angular.element(document.querySelectorAll('.'+className)[0])[0].clientWidth;
element.css({
width: classWidth+ 'px'
});
};
});
Upvotes: 0
Reputation: 1549
I have created a solution for your problem. First I will explain to you what I have done and why I did it this way.
One basic guideline in Angular is, that you should avoid dealing with DOM elements like divs in your controllers and instead do most things related to DOM elements in directives.
Directives allow you to bind functions to specific dom elements. In this case you want to bind a function to your first div, that gets the height and width of your element and exposes it to another element. I have commented my code below to show how I achieved this.
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
};
});
Now our scope variable style should contain an object with the current width and height of our "master" element even if the size of our master element changes.
Next up we want to apply this style to another element which we can achieve like so:
<span master class="a">{{content}}</span>
<div class="b" ng-style="style"></div>
As you can see the span above is our master element in the div is our "slave", which will always have the same width and height as it's master.
ng-style="style"
means that we add the css style contained in our scope variable called style to the span.
I hope you understand why and how I got to this solution, here is a plnkr with a demo displaying my solution in action.
Upvotes: 24