Reputation: 510
I'm facing a problem trying to set a css property on an element after his children have been rendered. In fact, I need to set the height of the parent element to be equals to the height of his first children. The problem is that his children are rendered in a ng repeat directive so I don't know when the element height would be computed.
In first place, i tried using an ng style directive. It works but I only needs to set the css once, and not everytime the scope changes, because my formula is likes : parentheight = firstChildHeight * scopeValue and scopeValue will change in execution time.
Thanks a lot for any help !
Upvotes: 1
Views: 2279
Reputation: 13651
For the first part, you can setup a watch that watches the calculated height of the first child. This is best done in a directive like this:
app.controller('MainCtrl', function($scope) { $scope.myMultiplier = 2; });
app.directive('firstChildHeight', function(){
return {
link: function(scope, element, attrs){
function firstChildHeight(){
return element.find(':first-child').height();
}
//This will only get evaluated one time
var multiplier = scope.$eval(attrs.heightMultiplier);
scope.$watch(firstChildHeight, function(height){
element.css('height', height*multiplier);
});
}
}
});
Notice how I read the multiplier from the scope only one time (I don't set up a watch to keep multiplier variable up to date). This should keep multiplier changing once it's been set originally (which I understand is what you want).
You can use it like this:
app.controller('MainCtrl', function($scope) {
$scope.myMultiplier = 2;
});
And then:
<body ng-controller="MainCtrl">
<div first-child-height height-multiplier="myMultiplier" style="background: red;">
<div>You should see me in red</div>
<div>I am in red too because height multiplier is 2</div>
<div>I don't have red</div>
</div>
</body>
As you can see, you don't really need to figure out when the ng-repeat will be done rendering, the height of the parent will always be in sync with the height of the first child multiplied by the value of the multiplier at the time the directive was compiled.
Here is a plunkr to play with:
http://plnkr.co/edit/DqmcKgq00jdwjs5IZh7H?p=preview
Did I understand your requirements correctly?
Upvotes: 2